简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM