Swift导航栏颜色

时间:2018-03-07 20:26:02

标签: ios swift uinavigationbar

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

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

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

2 个答案:

答案 0 :(得分:2)

我可以通过导航栏将ViewControllerB到ViewControllerA的颜色更改为完全正常的代码。我不确定你最初的问题是什么。这是我的代码:

ViewController A:

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 B:

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.
    }

}

它没有问题。

答案 1 :(得分:1)

<div class="bg"> <div class="container"> <div class="red"></div> <div class="blue" ></div> <div class="green" ></div> <div class="stick" ></div> </div> </div>在同一navigationBar堆栈中的所有视图控制器之间共享。

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