ios - 导航栏背景颜色

标签 ios swift uinavigationcontroller uinavigationbar

我正在尝试更改将在导航堆栈中推送的导航栏背景颜色。我在 Tabbar Controller 下使用导航 Controller 。
当我在更改导航栏颜色后插入 View Controller 时,第一次尝试它不起作用。当我通过点击标签栏项目重新加载此 View 时,它可以工作。

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

从另一个 Viewc Controller 调用的 View Controller

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

查看推送的 Controller
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

}

最佳答案

将此代码添加到您的 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

关于ios - 导航栏背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61489457/

相关文章:

ios - 从字典数组中读取 int(NSCFNumber)

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

swift - 编辑 - 我如何添加当答案错误时它会在正确答案中变成红色和绿色? swift 4.2

ios - Swift - 使 Sprite Kit 节点仅受重力影响?

ios - UINAvigationController -> setViewControllers 导致崩溃

ios - 导航 Controller 中 UIViewController 缺少后退按钮

ios - 如何创建新的 NSUrlSession(第一个 session 失效后)

ios - 没有mac的越狱cydia应用程序开发

ios - 如何删除使用 swift 代码添加的 3D touch 快速操作

ios - 一个带有两个导航栏的 Controller