Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Navigation Bar Title when different tab is selected

I am still fairly new to xcode.

I am trying to programatically change the navigation title when different tabs are selected in my UITabBarController.

I have a UItabBarController that creates the tab bar, then I have separate UIViewControllers which have different content for each of the tabs - this part works fine, however I cannot get the navigation title to change when different tabs are selected.

Here is the code for the main tab controller.

// SUPER VIEW DID LOAD

override func viewDidLoad() {
    super.viewDidLoad()
    
    // NAVIGATION ITEM
    navigationItem.title = "Job Information"
    navigationController?.navigationBar.prefersLargeTitles = true
    
    //setup our custom view controllers
    
    let jobInfo = page_jobInfo()
    let shots = page_shotList()
    let attachments = page_attachments()
    let notes = page_notes()
    
    jobInfo.tabBarItem.title = "Information"
    jobInfo.tabBarItem.image = UIImage(named: "jobInfo")
    
    shots.tabBarItem.title = "Shots"
    shots.tabBarItem.image = UIImage(named: "shots")
    
    attachments.tabBarItem.title = "Attachments"
    attachments.tabBarItem.image = UIImage(named: "attachments")
    
    notes.tabBarItem.title = "Notes"
    notes.tabBarItem.image = UIImage(named: "notes")
    
    viewControllers = [jobInfo, shots, attachments, notes]
}

Here is the code for the second tab button - The other 2 tabs are the same as this so didn't want to spam this feed with huge amounts of code.

// SUPER VIEW DID LOAD

override func viewDidLoad() {
    super.viewDidLoad()
    
    // NAVIGATION ITEM
    navigationItem.title = "Shot List"
    navigationController?.navigationBar.prefersLargeTitles = true
    
}
like image 966
spoax Avatar asked Dec 10 '22 08:12

spoax


1 Answers

Since your view controllers are embedded in UITabBarController, you should change its (tab bar controller's) navigationItem. Moreover, you should do that in viewWillAppear method instead of viewDidLoad, like so:

override func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  self.tabBarController?.navigationItem.title = "Bookmarks"
}
like image 63
Dan Karbayev Avatar answered Feb 15 '23 11:02

Dan Karbayev