简体   繁体   English

无法更改导航栏颜色

[英]Unable to change navigation bar color

I am trying to change the color of my navigation bar in a view which contains a UISearchController. 我试图在包含UISearchController的视图中更改导航栏的颜色。 I have previously set the color of my navigation bars for the whole app in my appDelegate, but i want this views nav bar to have a different color. 我以前在appDelegate中为整个应用程序设置了导航栏的颜色,但我希望这个视图导航栏有不同的颜色。 The issue is that i dont know which function to place the code such that it will override the appDelegate code. 问题是,我不知道放置代码的功能,以便它将覆盖appDelegate代码。 For example, viewDidLoad and viewWilAppear do not change the color when the view first loads, only after i enter and cancel the searchController. 例如,viewDidLoad和viewWilAppear在视图首次加载时不会更改颜色,只有在我输入和取消searchController之后。 Which function should i place the following? 我应该放置以下哪个功能?

UINavigationBar.appearance().backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)

There are two ways to do this. 有两种方法可以做到这一点。 You can either modify the appearance proxy that you have set up in the AppDelegate for the whole app, or you can modify the individual navigationbar for the particular screen. 您可以修改在AppDelegate中为整个应用程序设置的外观代理,也可以修改特定屏幕的单个导航栏。

When you dismiss the view - you need to reset the barTintColor in the viewWillDisappear. 当您关闭视图时 - 需要重置viewWillDisappear中的barTintColor。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // Set to new colour for whole app
    UINavigationBar.appearance().barTintColor = UIColor.blueColor()

    // Or, Set to new colour for just this navigation bar
    self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    //Revert to old colour, whole app
    UINavigationBar.appearance().barTintColor = UIColor.redColor()

    //Revert to old colour, just this navigation bar
    self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
}

您不应直接更改导航栏颜色,而应在viewWillAppear更改导航控制器的栏颜色,并在关闭视图时将其更改回来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM