根据视图控制器设置 UINavigationBar 颜色

set UINavigationBar color dependent on view controller

我想为每个视图控制器设置 UINavigationBar 颜色,而不是在应用程序委托中,因为那样做。

    UINavigationBar.appearance().backgroundColor = UIColor.whiteColor()
    UINavigationBar.appearance().translucent = false

我环顾四周,只是找不到如何做 this.I 试过这样做,但没有成功:

  override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
        self.navigationController?.navigationBar.tintColor = UIColor.blackColor()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

如何根据视图控制器而不是全局设置颜色?

据我了解,您需要在每个视图控制器中都有代码来设置导航栏颜色。尝试将此代码添加到每个视图控制器的 viewDidLoad

if let navController = self.navigationController {
    navController.navigationBar.tintColor = self.view.tintColor
}

这将使导航栏的色调与视图控制器的色调相同,但显然您可以将其更改为您想要的任何颜色。

这样做的好处是您可以直接复制粘贴它而无需更改任何内容,因此跨多个视图控制器实现它真的很容易(因为没有对视图控制器名称的具体引用)。

希望对您有所帮助。