快速更改后退按钮的字体和颜色

Ant*_*and 12 uinavigationbar ios swift swift2

我正在开发Swift 2.2中的应用程序.现在我想更改某个视图的后退按钮字体和颜色.有问题的视图有一个导航控制器作为它的父控制器.

我已尝试在ViewController的viewDidLoad中运行以下两行

self.navigationController!.navigationItem.backBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)
self.navigationItem.backBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

不会抛出任何错误,但它对后退按钮没有任何影响.我也试过运行这两个

self.navigationController!.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)   
self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

然而,这会引发错误(错误展开为零).我该如何正确更改导航栏后退按钮的字体和颜色?感觉就像我没有修改正确的物品......

Lio*_*ion 17

如果您想设置相同的颜色栏按钮隐含然后你appdelegatedidfinishlaunchingwithoption写,

 UINavigationBar.appearance().tintColor = UIColor.whiteColor() //your desired color here
Run Code Online (Sandbox Code Playgroud)

更新:

把它放在appdelegae中,

 UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Andes Rounded", size: 17)!], forState: .Normal) // your textattributes here
Run Code Online (Sandbox Code Playgroud)

更新2:

  UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UINavigationBar.classForCoder()]).setTitleTextAttributes(["attribute" : "value"], forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助:)


Dav*_*est 13

Swift 3.0的答案(根据Lion的回答):

let newFont = UIFont(name: "Avenir Next", size: 16.0)!
let color = UIColor.white

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.classForCoder() as! UIAppearanceContainer.Type]).setTitleTextAttributes([NSForegroundColorAttributeName: color, NSFontAttributeName: newFont], for: .normal)
Run Code Online (Sandbox Code Playgroud)

对于那些已经设法定制导航栏的其他部分而不是后退按钮的人来说,这是一种享受!


swi*_*TRL 5

我认为您应该在实际vc之前在vc中进行更改。看一下:UINavigationItem

编辑:例如,您可以编写:

let item = UIBarButtonItem(title: "Text goes here", style: .Plain, target: self, action: #selector(self.navigationController?.popViewControllerAnimated(_:)))

item.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Helvetica-Bold", size: 23)!], forState: .Normal)

navigationItem.backBarButtonItem = item
Run Code Online (Sandbox Code Playgroud)

在您的prepareForSegue方法中。


Mar*_*rta 5

斯威夫特 4

在 AppDelegate.swift 中

UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 15)!], for: .normal)
Run Code Online (Sandbox Code Playgroud)


Moh*_*ban 5

在斯威夫特 4.2

to change back button color
self.navigationController?.navigationBar.tintColor = .white
Run Code Online (Sandbox Code Playgroud)