cmii
cmii

Reputation: 3636

How to attach a UINavigationController subclass to its UIViewController?

I create a UINavigationController subclass:

class CustomNavigationViewController: UINavigationController {

    var imageview:UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationBar.setValue(true, forKey: "hidesShadow")
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.isTranslucent = true
        self.view.backgroundColor = UIColor.clear

        imageview = UIImageView(frame: CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: self.navigationBar.frame.height+20))
        imageview.image = UIImage(named: "navbar")
        self.navigationBar.addSubview(imageview)
    }
 }

In my storyboard, I set the UINavigationController as CustomNavigationViewController.

enter image description here

At run, my image in the navigationBar is correctly displayed.

But, I don't know how to make a reference to the CustomNavigationViewController in my HomeViewController class. I need to access to its imageview variable.

Upvotes: 0

Views: 78

Answers (1)

Ratul Sharker
Ratul Sharker

Reputation: 8011

HomeViewController's navigationController property already pointing to the same object when HomeViewcontroller is pushed into that CustomNavigationViewController. Just cast it into CustomNavigationViewController

Code

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if let customNavigation = self.navigationController as? CustomNavigationViewController {
       // here you got your `customNavigationController`'s object. 
       customNavigation.imageview // access it
    }
}

NB: Do not try to access the navigationController property of UIViewController, because in that time it won't be holding the navigation controller yet.

Upvotes: 1

Related Questions