嵌入式 tableview 的情节提要背景颜色 属性 不起作用?

Embedded tableview's storyboard background color property not working?

我展示了一个 tableview 控制器(嵌入在导航控制器中):

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)

我想在storyboard上设置导航栏背景色,代码改tvc.title

在上面的代码片段中,导航栏背景颜色需要通过代码(倒数第二行)进行设置,因为情节提要导航栏背景颜色设置不会改变其内容。导航栏背景色保持白色(默认)。 tvc.title 正确更改。

然而,当我如下更改代码时,导航栏背景颜色会根据情节提要选择而根据需要更改,但现在 tvc.title 无法通过代码设置。

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)

我的印象是我缺少一些基本的东西。

我想通过代码更改这两个属性。

如果你的故事板有这样的结构:

UINavigationController --> MyTableViewController

您可以像这样实例化 MyTableViewController 并且:

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