Fahim Rahman
Fahim Rahman

Reputation: 227

How can I Navigate to a viewController from a collectionView's didSelectItemAt which is inside a tableView cell?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        //let cell: HomeCollectionViewCell = homeCollectionView.dequeueReusableCell(withReuseIdentifier: "homeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "ReadOrDownloadViewController") as! ReadOrDownloadViewController

        navigationController.pushViewController(vc, animated: true)

    }

Here Xcode says " Use of unresolved identifier 'navigationController' "

The HomeCollectionViewCell is under a tableViewCell.

Upvotes: 0

Views: 482

Answers (1)

Yoel Jimenez del valle
Yoel Jimenez del valle

Reputation: 1278

you must set a delegate or a closure to the cell class to pass the action to the viewcontroller

closure:

class myCell: UITableViewCell{
   var closure: (() -> Void)?

since you set this class as the datasource and the delegate for the collectionView then rewrite this function as

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    closure?()
}

then in the viewController where you set the tableview Datasource then,

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.deque ....
cell.closure = {_ in
   let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "ReadOrDownloadViewController") as! ReadOrDownloadViewController
        navigationController.pushViewController(vc, animated: true)

for protocol is the same just set the delegate in the cell and call delegate function in the collectionView didTap item function

Upvotes: 1

Related Questions