Swift导航栏颜色

5

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

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

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


你把代码片段添加在哪里了(视图控制器生命周期方法中)? - Ahmad F
在根视图控制器和子视图控制器的viewWillAppear方法中 - pmax1
你也在调用super.viewWillAppear吗? - userx
@userx 这不会是问题的原因。 - Ahmad F
让我确认一下您的问题,导航到最后一个视图控制器(应该有一个蓝色的栏)时可以正常工作,但返回到上一个视图控制器会使其栏也变为蓝色而不是红色,因此您想要让它再次变成红色? 这就是您的问题吗? - Ahmad F
完全正确 @AhmadF - pmax1
2个回答

3
我可以使用你的代码完美地将从ViewControllerB到ViewControllerA的导航栏颜色更改。我不确定你最初的问题是什么。这是我的代码,它有效地解决了问题:

视图控制器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)
    }


}

视图控制器 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.
    }

}

它没有出现任何问题。


3

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

如果您想为特定的视图控制器更改其外观,则必须在显示视图控制器时设置新样式,并在解除视图控制器时将其删除。例如,这可以在视图控制器的 viewWillAppear/viewWillDisappear 中完成。


成功了!但是现在返回到上一个视图控制器时的颜色过渡有点卡顿。是否有一种解决方法可以在上一个视图控制器出现之前设置颜色? - pmax1
https://dev59.com/2FgQ5IYBdhLWcg3wRR5j - Ludovic Landry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接