簡體   English   中英

導航欄背景顏色

[英]NavigationBar Background Color

我正在嘗試更改將在導航堆棧中推送的導航欄背景顏色。 我在標簽欄 controller 下使用導航 controller。 當我在更改導航欄顏色后推送視圖 controller 時,第一次嘗試它不起作用。 當我通過點擊標簽欄項目重新加載此視圖時,它可以工作。

為什么它在第一次嘗試時不起作用?

查看 controller 從另一個 Viewc 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)
}

查看推送的控制器

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

在此處輸入圖像描述

您應該創建 UINavigationController 的子類並對其進行自定義,如果您使用的是 Interface Builder,則可以在識別檢查器中設置 NavigationController 自定義 class。

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

      }

在此處輸入圖像描述

你可以在這里閱讀更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM