Search code examples
swiftuitableviewuinavigationcontroller

Embedded tableview's storyboard background color property not working?


I present a tableview controller (which is embedded in a navigation controller) like that:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tvc = storyboard.instantiateViewController(withIdentifier: "tvcID") as! MyTableViewController
tvc.title = "My tableview title" // WORKS
let nc = UINavigationController(rootViewController: tvc)
nc.navigationBar.backgroundColor = UIColor.blue // NOT POSSIBLE USING STORYBOARD
self.present(nc, animated: true, completion: nil)

I'd like to set the navigation bar background color on storyboard, and change tvc.title by code.

In sniplet above, the navigation bar background color requires to be set by code (2nd last line) since the storyboard Navigation Bar Background color setting doesn't change as to what it says. The navigation bar background color remains white (default). tvc.title changes properly.

However when I change my code as follows, the navigation bar background color changes as desired according storyboard selection, but now tvc.title cannot be set by code.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tvc = storyboard.instantiateViewController(withIdentifier: "tvcID") as! MyTableViewController
tvc.title = "My tableview title" // NOW THIS DOESN'T WORK ANYMORE
let nc = storyboard.instantiateViewController(withIdentifier: "ncID") as! UINavigationController
// nc.navigationBar.backgroundColor = UIColor.blue // NOT REQUIRED ANYMORE
self.present(nc, animated: true, completion: nil)

I'm under the impression that I'm lacking something fundamental here.

I would like to change both properties by code.


Solution

  • If your storyboard has the structure like this:

    UINavigationController --> MyTableViewController

    You could instantiate MyTableViewController like this and :

    guard let navController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as? UINavigationController else { return }
    guard let tvc = navController.viewControllers.first as? MyTableViewController else { return }
    tvc.title = "Test title"
    navController.navigationBar.barTintColor = UIColor.green