NavigationBar背景色

问题描述 投票:2回答:2

我正在尝试更改将在导航堆栈中推送的导航栏背景颜色。我在Tabbar控制器下使用导航控制器。当我在更改导航栏颜色后按下视图控制器时,第一次尝试它不起作用。当我通过点击选项卡项重新加载此视图时,它会起作用。

为什么它第一次尝试不起作用?

从另一个Viewc控制器调用的视图控制器

func showProjectDetails(indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "MyTaskVC") as! MyTaskVC
    vc.viewMode = .ProjectDetails
    vc.currentProjectName = projects[indexPath.row].projectName
    navigationController?.pushViewController(vc, animated: true)
}

推过的浏览器

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
let appearance = UINavigationBarAppearance()
        appearance.backgroundColor = .green
        appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

        UINavigationBar.appearance().tintColor = .white
        UINavigationBar.appearance().standardAppearance = appearance
        UINavigationBar.appearance().compactAppearance = appearance
        UINavigationBar.appearance().scrollEdgeAppearance = appearance

}
swift uinavigationcontroller uinavigationbar ios13
2个回答
0
投票

viewDidLoad()中添加此代码

override func viewDidLoad() {
        super.viewDidLoad()

      if  let navigationBar = navigationController?.navigationBar {
        let appearance = UINavigationBarAppearance()
        appearance.backgroundColor = .green
        appearance.titleTextAttributes = [.foregroundColor: UIColor.red]
        appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

        let barAppearence = UIBarButtonItemAppearance()
        barAppearence.normal.titleTextAttributes = [.foregroundColor: UIColor.yellow]

        appearance.buttonAppearance = barAppearence

        navigationBar.scrollEdgeAppearance = appearance
        navigationBar.compactAppearance = appearance
        navigationBar.standardAppearance = appearance

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

enter image description here


-2
投票

您应该创建UINavigationController的子类并对其进行自定义,如果您使用的是Interface Builder,则可以在Identify Inspector中设置NavigationController自定义类。

    import UIKit

    class YourNavigationController: UINavigationController { 

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            let barAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [YourNavigationController.self])
            barAppearance.tintColor = UIColor(named: "Blue" 
        } 

        override func viewDidLoad() {
            super.viewDidLoad()                        
        }    

      }

enter image description here

您可以阅读更多here

© www.soinside.com 2019 - 2024. All rights reserved.