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

Hai*_*faq 4 uiviewcontroller uinavigationcontroller uicollectionview uicollectionviewcell swift

我有一个 UICollectionViewCell 类“ ProductCell ”;我正在尝试访问当前的导航控制器以更新栏按钮图标。我尝试了以下代码,因为这是我在其他 UIViewController 中使用的代码:

    let nav = self.navigationController as! MFNavigationController
    nav.updateCartBadgeValue()
Run Code Online (Sandbox Code Playgroud)

然而它指出

ProductCell 类型的值没有成员 navigationController

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

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

let navigationController = application.windows[0].rootViewController as! UINavigationController
Run Code Online (Sandbox Code Playgroud)

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

任何帮助深表感谢

谢谢

Ban*_*tor 5

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

controller()将返回类型为“ UIViewController Then”的最近响应者,在返回的控制器上,您只需要找到其导航控制器。你可以navigationController()在这里使用。