如何更改导航栏后退按钮的字体? [英] How can I change the font of the back button for my navigation bar?

查看:22
本文介绍了如何更改导航栏后退按钮的字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改导航栏后退按钮的字体.

How can I change the font of the back button for my navigation bar.

后退按钮是后退"或上一个视图控制器的标题.

The back button is either "back" or the title from the previous view controller.

我认为这个 viewDidLoad 会起作用:

I thought this viewDidLoad would work:

navigationController?.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "FONTNAME", size: 20)!], forState: UIControlState.Normal)

但是 leftBarButton? 可选返回 nil.

推荐答案

刚刚测试了你的代码,看起来行返回 nil 的原因实际上是因为 name: "FONTNAME" 返回零.因此,如果您将该 name 属性设置为有效的字体名称,则代码应该可以正常运行而不会出错——即使 navigationController?.navigationItem.leftBarButtonItem 显式设置为 nil.

Just tested your code and it seems the reason that line is returning nil is actually because name: "FONTNAME" returns nil. So if you set that name attribute to a valid font name, the code should run without an error -- even if navigationController?.navigationItem.leftBarButtonItem is explicitly set to nil.

但无论如何,正如我通过测试所看到的,这条线不会给你明显想要的结果.领先的 navigationController 选项不应该在那里,因为它访问您的 UINavigationController 而不是当前视图.只需使用 UIViewController 自己的 navigationItem 属性来直接访问它的 leftBarButtonItem,例如:

But regardless, also as I've seen through testing, this line won't give you the result you apparently want. The leading navigationController optional shouldn't be there since it accesses your UINavigationController and not the current view. Simply use the UIViewController's own navigationItem property to access its leftBarButtonItem directly, ex:

let backButton = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
navigationItem.leftBarButtonItem = backButton
navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Chalkduster", size: 20)!], forState: UIControlState.Normal)

编辑:从您在此答案下发布的评论来看,您似乎实际上并不想设置 leftBarButtonItem 而是 backBarButtonItem,因为除了返回上一个视图控制器之外,您不想实现自定义操作.

Edit: From the comment you posted under this answer, it seems as if you don't actually want to set the leftBarButtonItem but the backBarButtonItem because you don't want to implement a custom action beyond going back to the previous view controller.

因此,在之前的视图控制器中(即您想要显示自定义后退按钮项目之前的视图),您可以设置自定义后退按钮而无需执行如下操作:

So in that previous view controller (i.e. the view before you want to show your custom back button item), you can set your custom back button without an action like so:

let backButton = UIBarButtonItem(title: "< Back", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
backButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Chalkduster", size: 20)!], forState: UIControlState.Normal)
navigationItem.backBarButtonItem = backButton

这篇关于如何更改导航栏后退按钮的字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆