UINavigationBar Swift中的文本颜色

我将如何去改变Swift中的UINavigationBar的颜色?

网上大多数事情都是这样做的:

 [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; 

我翻译成的

 let titleDict: NSDictionary = ["NSForegroundColorAttributeName": UIColor.whiteColor()] self.navigationController.navigationBartitleTextAttributes = titleDict //self is referring to a UIViewController 

但它不起作用。 我已经改变了背景和button的颜色,但文字的颜色不会改变。 有任何想法吗?

使用NSForegroundColorAttributeName作为键,而不是"NSForegroundColorAttributeName"string。

 let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationController.navigationBar.titleTextAttributes = titleDict 

您也可以在AppDelegate.swift文件中更改应用程序中的所有UINavigationController外观。 只需在application:didFinishLaunchingWithOptions放入以下代码application:didFinishLaunchingWithOptions函数:

 var navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = UIColor.YourNavigationButtonsColor() // Back buttons and such navigationBarAppearace.barTintColor = UIColor.YourBackgroundColor() // Bar's background color navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.YourTitleColor()] // Title's text color 

信誉: Coderwall的博客文章

Swift 2.0

 self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] 

Swift 3+

 self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] 

Swift 4.0

 self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white] 
  //Nav Bar Title self.title = "WORK ORDER" self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] 

Swift 3

 UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .selected) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.black], for: .normal) 

我使用像:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] return true } 
  let titleDict = [NSForegroundColorAttributeName: UIColor.white] self.navigationController?.navigationBar.titleTextAttributes = titleDict