navigationController?.pushViewController 不工作

navigationController?.pushViewController is not working

我有一个集合视图控制器。在 collectionView 单元格 中,我有一个标签,我将其设为可点击 push 到 nextViewController。

我知道 navigationController 中有这个问题。但我是 swift 的新手,所以无法修复。希望大家能帮帮我。

这是我的 SceneDelegate:

    let layout = UICollectionViewFlowLayout()
    // Create the root view controller as needed
    let nc = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
    
    let win = UIWindow(windowScene: winScene)
    win.rootViewController = nc
    win.makeKeyAndVisible()
    window = win
    

和我的标签:

    let text = UILabel()
    text.text = "something"
    text.isUserInteractionEnabled = true
    self.addSubview(text)
    
    let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopularCellTwo.labelTapped))
    text.addGestureRecognizer(gestureRecognizer)
}

    @objc func labelTapped() {
        let nextVC = NextViewController()
        self.navigationController?.pushViewController(nextVC, animated: true)
        print("labelTapped tapped")
    
    }

我还添加了屏幕截图。当我点击“某事”时,它应该进入下一页。 [1]: https://i.stack.imgur.com/4oYwb.png

self.navigationController?.pushViewController(nextVC, animated: true)

你指的 self 是什么?因为你无法推进 child class 你有 HomeController 我假设它是你的 parent 控制器。

只是尝试调试什么 self 这可以通过调试或条件调试来尝试

print (self)
if (self.isKind(of: YourParentController.self)) {
// make push
}

或尝试检查,看看 navigationcontroller 是否有 nil 值

这是使用闭包的方法。我在 UICollectionViewCell sub-class 中创建了一个 closure 参数。当标签手势目标被击中时,我调用闭包,然后在 HomeController.

中执行导航
class HomeController: UICollectionViewController {
    //...
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = // dequeue cell
        cell.labelTap = { [weak self] in
            guard let self = self else { return }
            let nextVC = NextViewController()
            self.navigationController?.pushViewController(nextVC, animated: true)
            print("navigated")
        }
        return cell
    }
}

class CollectionViewCell: UICollectionViewCell {

    var labelTap: (() -> Void)?
    @objc func labelTapped() {
        print("labelTapped tapped")
        labelTap?()
    }
}

您可以使用委托或闭包来完成此操作

class ItemCollectionViewCell: UICollectionViewCell {
   var onTapGesture: (() -> ())?
}

然后在你的函数中做

    @objc func labelTapped() {
       
         onTapGesture?()
    }

在你的控制器中

class HomeController: UICollectionViewController {
    //...
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = // dequeue cell
        cell.onTapGesture = { [unowned self] in
            let nextVC = NextViewController()
            self.navigationController?.pushViewController(nextVC, animated: true)
           
        }
        return cell
    }
}