Swift: 从 UICollectionViewCell 访问当前导航控制器

Swift: Accessing current navigation controller from a UICollectionViewCell

我有一个 UICollectionViewCell class "ProductCell";我正在尝试访问当前的导航控制器以更新 barbuttonicon。我尝试了以下代码,因为这是我在其他 UIViewControllers 中使用的代码:

    let nav = self.navigationController as! MFNavigationController
    nav.updateCartBadgeValue()

但是它指出

value of type ProductCell has no member navigationController

我知道这不是 UIViewController 但您肯定能够以同样的方式访问当前的导航控制器吗?

我也知道您可以通过以下方式使用UIApplication访问导航控制器:

let navigationController = application.windows[0].rootViewController as! UINavigationController

不过我不确定这是否是个好方法。

非常感谢任何帮助

谢谢

除非事情发生变化,否则这是一个很好的方法。给你一个更混乱的解决方案的例子......你可以添加一个

let hostViewController:UIViewController 

属性 到您的单元格并添加一个初始化程序来处理它

let cell = ProductCell(vc: self)

但我认为这不是更好的方法。你的建议很好。

let navigationController = application.windows[0].rootViewController as! UINavigationController

最简单的方法是向您的单元格 class 添加一个 属性 弱引用 UINavigationController

weak var navigationController: UINavigationController?

您需要在 cellForRow(atIndexPath:_) 方法中分配它。

let cell = tableView.dequeueReusableCell(withIdentifier: "yourReuseID") as! YourCellClass
cell.navigationController = navigationController //will assign your viewController's navigation controller to the cell

return cell

UIResponder链会在这里提供帮助。

您可以搜索响应链以找到任何视图的控制器

extension UIView {

    func controller() -> UIViewController? {
        if let nextViewControllerResponder = next as? UIViewController {
            return nextViewControllerResponder
        }
        else if let nextViewResponder = next as? UIView {
            return nextViewResponder.controller()
        }
        else  {
            return nil
        }
    }

    func navigationController() -> UINavigationController? {
        if let controller = controller() {
            return controller.navigationController
        }
        else {
            return nil
        }
    }
}

controller() 将 return 类型为 UIViewController 的最接近的响应者 然后在 returned 控制器上你只需要找到它的导航控制器。你可以在这里使用navigationController()