【问题标题】:UINavigationBar failing to change colorUINavigationBar 无法更改颜色
【发布时间】:2017-08-24 07:57:50
【问题描述】:

我正在尝试以编程方式更改导航栏的背景颜色/栏色调颜色。

我尝试了几个示例,但有些示例需要在每个视图控制器中编写代码,这对我来说不是最有意义的,因为我希望将其子类化以减少重复代码。

我创建了 UINavigationBar 的子类(因为我也想改变高度)。

我已成功更改高度,它在我的应用程序中有效。但是,在更改颜色时,它似乎不起作用。

class Navbars: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    //self.backgroundColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    //self.barTintColor = Logic.UIColorFromRGB(rgbValue: 0xff0864, alp: 1.0)
    self.backgroundColor = UIColor.blue
    self.barTintColor = UIColor.blue
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func draw(_ rect: CGRect) {

}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 205)
}
}

高度发生了变化,所以我认为在 init 函数中使用代码来改变它的颜色会起作用,但它不起作用,我不知道为什么。

我什至尝试将 UINavigationController 子类化,但仍然没有任何反应。

class NavControllers: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationBar.barTintColor = UIColor.brown

    // Do any additional setup after loading the view.
}

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

}

如果有人知道我哪里出错了,那将不胜感激。谢谢!

【问题讨论】:

    标签: ios swift colors uinavigationcontroller uinavigationbar


    【解决方案1】:

    试试这个代码

    ////////////////// set navigation bar tint color ///////////////
        self.navigationController.navigationBar.barTintColor = (your color here);
    

    为我工作:)。

    【讨论】:

      【解决方案2】:

      在操场上尝试以下对我来说很好......

      class NavController: UINavigationController {
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              navigationBar.barTintColor = .red
          }
      }
      
      let viewController = UIViewController()
      viewController.view.backgroundColor = .white
      
      let navController = NavController(rootViewController: viewController)
      

      【讨论】:

        【解决方案3】:

        对于那些将 xcode 更新到 11.04 版本的人,这些解决方案不起作用。这就是为什么,在 viewWillAppear 中添加此代码

        guard let navBar = navigationController?.navigationBar else {fatalError("Navigation controller does not exists.")}
        
        let bgColor = UIColor.red // change your choice
        
        navBar.backgroundColor = bgColor
        navBar.standardAppearance.backgroundColor = bgColor
        navBar.scrollEdgeAppearance?.backgroundColor = bgColor
        

        【讨论】:

          猜你喜欢
          • 2018-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多