self.navigationController?.pushViewController 不起作用 Swift

10

我有一个CollectionViewController,当我试图点击单元格并导航到相应的ViewControllers时,它不起作用。我该如何解决这个问题。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell:AddOptionCollectionViewCell = collectionView.cellForItem(at: indexPath) as! AddOptionCollectionViewCell

    if (cell.name.text == "CONTRAST"){
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

        let newViewController = storyBoard.instantiateViewController(withIdentifier: "ContrastViewController") as! ContrastViewController
        self.navigationController?.pushViewController(newViewController, animated: true)
    }

2
不管和问题是否相关,在这种情况下永远不要从视图(单元格)检索数据,而是应该从模型(数据源)获取。 - vadian
self 在导航控制器中吗? - rmaddy
此外,你的 if 语句总是会返回 true。我建议在继续之前仔细阅读 UICollectionView 的文档。 - lurning too koad
此外,通常应优先使用较新的 show(newViewController, sender: self) 而不是直接访问导航控制器。 - DeFrenZ
问题得到解决。 - Junaid Ali
2个回答

13
我认为这个问题是由于您的CollectionViewController类的导航堆栈值为nil导致的。因此,首先转到storyboard并选择CollectionViewController类,将NavigationController嵌入其中。完成后尝试运行它,它会起作用。
祝好运。

5

在我的情况下,我错误地将 MainViewController 添加到了 window.rootViewController,而不是先将其添加到 UINavigationController 中,然后使用导航作为 rootViewController

SceneDelegate.swift 中应该是这样的:

 let navigationController = UINavigationController()
 navigationController.pushViewController(MainRouter.createModule(using: navigationController), animated: false)
 window.rootViewController = navigationController
 window.makeKeyAndVisible()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接