Swift: How to use “didSelectItemAtIndexPath” in UITableViewController(contains UICollectionView)?

后端 未结 2 590
北荒
北荒 2021-01-15 14:49

I have a UITableViewController, inside the TableViewCell, it\'s a UICollectionView. I want to pass the data from the CollectionV

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 15:16

    The way you are going is correct, but you are creating one mistake.Try to implement UICollectionViewDelegate method didSelectItemAtIndexPath also inside TableViewCell and remove it from the HomePageTableViewController.

    Now declare one protocol, after that create its instance inside TableViewCell and implement the protocol in the HomePageTableViewController, after that in the didSelectItemAtIndexPath use that delegate instance to call the method like this.

    protocol PostDelegate {
        func selectedPost(post: Posts)
    }
    

    Now create its instance inside TableViewCell and call this delegate method in the didSelectItemAtIndexPath.

    class TableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
         var posts1: [Posts] = [Posts]()
         var posts2: [Posts] = [Posts]()
         var categories: [Category] = [Category]()
         var selectedPost1: Posts?  
         var postDelegate: PostDelegate?
    
         func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
             postDelegate?. selectedPost(self.posts1[indexPath.row])
         }
    }
    

    Now implement this PostDelegate protocol inside HomePageTableViewController

    class HomePageTableViewController: UITableViewController,UICollectionViewDelegate { 
    
    
         //Your code 
    
         func selectedPost(post: Posts) {
             //You will get your post object here, do what you want now
         }
    }
    

    Note: Inside cellForRowAtIndexPath don't forgot to set the delegate of postDelgate with your HomePageTableViewController like this

    tableViewCell.postDelegate = self
    

    Edit:

    func selectedPost(post: Posts) {
        //You will get your post object here, do what you want now
        self.performSegueWithIdentifier("goToDetail", sender: post)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let post = sender as! Posts
        let postDetailPage = segue.destinationViewController as? DetailViewController
        postDetailPage.passPost = post
    }
    

提交回复
热议问题