改变iOS导航栏的颜色

52

我想要改变导航栏的颜色,但我发现只有在导航栏是根导航栏的情况下才行。

我正在尝试这样做:

self.navigationController?.navigationBar.translucent = true

self.navigationController!.navigationBar.barTintColor = UIColor.blueColor()

我的所有ViewControllers都与导航控制器相关联。 但是没有任何变化。 实际上,我尝试从故事板中做相同的事情,但只有在第一个导航器中才有效。

我尝试阅读与此问题相关的所有信息,但什么都没有找到。

我可以像这样添加项目到导航栏

let HomeImage = UIImage(named: "home")!
    let Home : UIBarButtonItem = UIBarButtonItem(image: HomeImage,  style: .Plain, target: self, action: "home:")
    navigationItem.rightBarButtonItem = Home

1
最新答案请查看此链接 https://dev59.com/XGQn5IYBdhLWcg3wNk04#55391324 - Naresh
10个回答

99

实际上,我发现解决方法是在AppDelegate.swift文件中使用:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    UINavigationBar.appearance().barTintColor = UIColor(red: 0, green: 0/255, blue: 205/255, alpha: 1)
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]

    return true
}

然后在每个视图控制器中,如果我们需要另一个背景颜色或其他东西

  1. 转场应该与“show”不同

  2. 使用函数viewWillAppear

 override func viewWillAppear(animated: Bool) {
     super.viewWillAppear(animated)
     self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
     self.navigationController?.navigationBar.tintColor = UIColor.blueColor()
     self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()]
}

1
它能够工作,但在两个控制器之间没有实现无缝过渡。 - Codetard
使用未解决的标识符“NSForegroundColorAttributeName”。 - Takasur
2
对于Swift 4的使用,请使用NSAttributedStringKey.foregroundColor。 - Dekel Maman
同时确保您的导航栏中没有背景图像(覆盖了背景颜色)。我的导航栏中有一个意外设置的背景图像,这让我花费了几个小时来检查它... - Wei WANG
@Anthony 我又遇到问题了。这段代码成功改变了标题的字体颜色。但是如果跳转到其他视图控制器然后返回,标题的字体颜色仍然没有改变。 - 鸡肉味嘎嘣脆

55

更新至Swift 3

    UINavigationBar.appearance().barTintColor = .black
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    UINavigationBar.appearance().isTranslucent = false

Swift 4

    UINavigationBar.appearance().barTintColor = .black
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
    UINavigationBar.appearance().isTranslucent = false

Swift 5

    UINavigationBar.appearance().barTintColor = .black
    UINavigationBar.appearance().tintColor = .white
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    UINavigationBar.appearance().isTranslucent = false

我需要在AppDelegate.swift文件中做这个吗? - TheSwiftGuy77
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 设置导航栏..... } - iAj
@PrashannaChudal 是的,你可以这样做。在上面的AppDelegate方法中编写代码(请参见上面的评论)。 - iAj

21

Swift 4.2:

    //To change Navigation Bar Background Color
    UINavigationBar.appearance().barTintColor = UIColor.blue
    //To change Back button title & icon color
    UINavigationBar.appearance().tintColor = UIColor.white
    //To change Navigation Bar Title Color
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

Swift 3.x:

//To change Navigation Bar Background Color
UINavigationBar.appearance().barTintColor = UIColor.blue
//To change Back button title & icon color
UINavigationBar.appearance().tintColor = UIColor.white
//To change Navigation Bar Title Color
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

1
Swift 4.2,使用 NSAttributedString.Key.foregroundColor 替代。 - cumanzor
由于某些奇怪的原因,Xcode 10中的自动完成未建议barTintColor作为UINavigationBar.appearance()的属性,但复制/粘贴您的代码确实编译并工作。谢谢! - Vilmir

7

如果要在整个应用程序中更改导航栏的主题颜色,则可以使用UiNavigation bar外观来完成。

UINavigationBar.appearance().barTintColor = UIColor.redColor()

4
如果您的视图控制器嵌套在导航控制器中,则可以删除默认的导航栏,并为该视图控制器使用自定义导航栏。

您可以这样做

UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0)

4

请将以下更新应用于AppDelegate.Swift文件,即:

UINavigationBar.appearance().barTintColor = UIColor(red:x.xx, green:x.xx, blue:x.xx, alpha:1.0)

参考下面的示例:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UINavigationBar.appearance().barTintColor = UIColor(red:0.03, green:0.25, blue:0.11, alpha:1.0)
    UINavigationBar.appearance().tintColor = UIColor.white
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

2
self.navigationController?.navigationBar.barTintColor = UIColor.gray

1

For black nav bar try this:

navigationController?.navigationBar.barStyle = .black

这只是更改样式,而不是条形颜色。 :) - Muhammad Shauket

0
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];

0

解决 SwiftUI 的这个问题:

            init() {
        //         For .navigationBarTitle(Text("Update"), displayMode: .automatic)
        
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.backgroundColor = .black
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        
        // to make everything work normally
        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        
        //         For .navigationBarTitle(Text("Update"), displayMode: .inline)
        
        //        UINavigationBar.appearance().barTintColor = .black
        //        UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
    }
    
    var body: some View {
        NavigationView {
            //                     Text("Screen")
            let HomeImage = UIImage(named: "home")!
            let Home : UIBarButtonItem = UIBarButtonItem(image: HomeImage,  style: .Plain, target: self, action: "home:")
            navigationItem.rightBarButtonItem = Home
                .navigationBarTitle(Text("Update"), displayMode: .automatic)
        }
        // that means only show one view at a time no matter what device I'm working
        .navigationViewStyle(StackNavigationViewStyle())
    }

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