Swift 导航栏颜色

Swift Navigation Bar Color

是否可以为导航层次结构中的 单个 视图控制器设置导航栏颜色?让默认的导航栏颜色为红色,并且该行中的最后一个视图控制器应该是蓝色的。我已经使用这两行为所述视图控制器的导航栏着色:

navigationController?.navigationBar.barTintColor = .blue
navigationController?.navigationBar.tintColor = .white

但是当返回时(例如通过按后退按钮)导航栏保持蓝色。使用上面的代码将颜色设置回红色不会执行任何操作。

navigationBar 在同一 UINavigationController 堆栈中的所有视图控制器之间共享。

如果要更改它以查找特定的视图控制器,则必须在显示视图控制器时设置新样式,并在关闭视图控制器时将其删除。例如,这可以在视图控制器的 viewWillAppear/viewWillDisappear 中完成。

我可以让导航栏将颜色从 ViewControllerB 更改为 ViewControllerA,非常适合您的代码。我不确定您最初的问题是什么。这是我的有效代码:

ViewController答:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = .red
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func buttonAction(_ sender: Any) {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "Second")
        //self.present(controller, animated: true, completion: nil)
        self.navigationController?.pushViewController(controller, animated: true)
    }


}

ViewController乙:

import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.barTintColor = .blue
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

它没有问题。