Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Accessing current navigation controller from a UICollectionViewCell

I have a UICollectionViewCell class "ProductCell"; I am trying to access the current navigation controller in order to update a barbuttonicon. I have tried the following code as this is what I use in my other UIViewControllers:

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

However it states that the

value of type ProductCell has no member navigationController

I am aware that this is not a UIViewController but surely you should be able to access the current navigation controller the same way?

I also know that you can access the navigation controller by using UIApplication in the following way:

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

I am not sure if that is a good way of doing it though.

Any help is much appreciated

Thanks

like image 296
Haider Ashfaq Avatar asked Sep 05 '25 10:09

Haider Ashfaq


1 Answers

UIResponder chain will help here.

You can search the responder chain to find the controller for any view

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() will return the closest responder that is of type UIViewController Then on the returned controller you just need to find its navigation controller. You can use navigationController() here.

like image 124
BangOperator Avatar answered Sep 08 '25 21:09

BangOperator