mattgabor
mattgabor

Reputation: 2084

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.

Upvotes: 0

Views: 2215

Answers (1)

BaseZen
BaseZen

Reputation: 8718

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.

Upvotes: 2

Related Questions