Swift中的UINavigationBar文本颜色

ccl*_*oyd 61 navigation text colors uinavigationbar swift

我如何改变UINavigationBarSwift中的颜色?

网上的大多数事情都说要做以下事情:

[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
Run Code Online (Sandbox Code Playgroud)

我翻译成了哪个

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

但它不起作用.我已经改变了背景和按钮颜色,但文本颜色没有改变.有任何想法吗?

Kre*_*iri 102

使用NSForegroundColorAttributeName为重点,而不是"NSForegroundColorAttributeName"字符串.

let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = titleDict
Run Code Online (Sandbox Code Playgroud)

  • 根据Swift 1.2更新,语法需要是这样的`let titleDict:NSDictionary = [NSForegroundColorAttributeName:UIColor.whiteColor()] self.navigationController!.navigationBar.titleTextAttributes = titleDict as [NSObject:AnyObject]` (6认同)
  • 根据Swift 2.2:`let titleDict:NSDictionary = [NSForegroundColorAttributeName:UIColor.whiteColor()] self.navigationController!.navigationBar.titleTextAttributes = titleDict as?[String:AnyObject]` (2认同)

Lou*_*cin 35

您还可以UINavigationController在AppDelegate.swift文件中更改应用中的所有外观.只需将以下代码放在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
Run Code Online (Sandbox Code Playgroud)

信用:Coderwall的博客文章

  • 感谢您在色调/条形色调颜色旁边发表评论,这帮助我意识到我做错了什么,从而结束了我的头撞墙循环。:D (2认同)

Das*_*oga 33

Swift 3+

self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
Run Code Online (Sandbox Code Playgroud)

Swift 4.0

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
Run Code Online (Sandbox Code Playgroud)


Jas*_*onH 28

Swift 2.0

self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
Run Code Online (Sandbox Code Playgroud)