简体   繁体   中英

Can I inherit from a UINavigationController in my UIViewController?

I am trying to create a custom navigation bar in my navigation controller that persists through each view after the initial navigation controller. I set up the navigation bar in a custom UINavigationController class, and I am trying to inherit the navigation controller's properties in my UIViewController custom class (the first View Controller after the nav controller)

Here is the syntax I am using, where HomePageViewController is my UIViewController that I want to inherit the Navigation Bar and numberInput is a UITextField in my HomePageViewController:

SearchNavigationController.swift

class SearchNavigationController: UINavigationController {

override func viewDidLoad() {
     super.viewDidLoad() 
     // Set up custom navigation bar
}

HomePageViewController.swift

class HomePageViewController: SearchNavigationController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var numberInput: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()

    numberInput.delegate = self 
}

However, when my app calls numberInput.delegate = self, I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.

But when I replace SearchNavigationController with UIViewController it works.

A UINavigationController does not manage views -- it manages other UIViewControllers -- so it will not initialize any random @IBOutlets. It only cares about initializing its navigation bar and connecting to its child view controllers.

I think you misunderstand how to "inherit" (not the right word) your navigation bar in your child view controllers. The child view controllers must be a subclass of UIViewController . Then @IBOutlets act normally. As long as they are managed by a UINavigationController by virtue of creating the proper 'show' segues, they get decorated automatically with that UINavigationController 's nav bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM