ios 如何更改导航栏后退按钮的字体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27583346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change the font of the back button for my navigation bar?
提问by Kyle Goslan
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.
后退按钮是“后退”或上一个视图控制器的标题。
I thought this viewDidLoad
would work:
我认为这viewDidLoad
会奏效:
navigationController?.navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "FONTNAME", size: 20)!], forState: UIControlState.Normal)
but the leftBarButton?
optional returns nil
.
但leftBarButton?
可选的回报nil
。
采纳答案by Lyndsey Scott
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.
刚刚测试了您的代码,似乎行返回的原因nil
实际上是因为name: "FONTNAME"
返回 nil。因此,如果您将该name
属性设置为有效的字体名称,则代码应该可以正常运行——即使navigationController?.navigationItem.leftBarButtonItem
明确设置为 nil。
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:
但无论如何,正如我通过测试所看到的,这条线不会给你明显想要的结果。前导navigationController
选项不应该在那里,因为它访问您的UINavigationController
而不是当前视图。只需使用UIViewController
自己的navigationItem
属性leftBarButtonItem
直接访问它,例如:
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)
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.
编辑:从您在此答案下发布的评论来看,似乎您实际上并不想设置leftBarButtonItem
但是,backBarButtonItem
因为除了返回上一个视图控制器之外,您不想实现自定义操作。
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
回答by Vexy
If you need to change font style entirelyacross you app (aka. each navigation button), preferred method is to use UIBarButtonItem.appearance()
proxy.
如果您需要在整个应用程序中完全更改字体样式(也就是每个导航按钮),首选方法是使用UIBarButtonItem.appearance()
代理。
Sample code snippet would look like this:
示例代码片段如下所示:
SWIFT 3.0+
斯威夫特 3.0+
//make sure font name u use below *actually* exists in the system !
//if it doesn't app will crash because we're force unwrapping an optional (see below) !!!
let customFont = UIFont(name: "customFontName", size: 17.0)!
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: customFont], for: .normal)
It is wise to put this code snippet somewhere at the beginning of your AppDelegate.swift
file because font stylization has to happen each time the app launches. Also, you're safe to put this code in any other place(eg. Presenter
class) where you do your UI stylization and customization. As soon as this code gets executed, all your BarButtons will be customized thereafter.
将此代码片段放在AppDelegate.swift
文件开头的某个位置是明智的,因为每次应用程序启动时都必须进行字体样式化。此外,您可以安全地将此代码放在您进行 UI 样式化和自定义的任何其他地方(例如Presenter
类)。执行此代码后,您的所有 BarButton 都将在此后进行自定义。
BUTas a true Swift , you should first optionally unwrap your font and eventually fallback to system font if it's not found or any other possible issue arise during font loading.
但是作为真正的 Swift ,您应该首先有选择地解开您的字体,如果未找到或在字体加载期间出现任何其他可能的问题,则最终回退到系统字体。
var textAttributes: [String:Any]
//custom font setup
let fontColor = UIColor.purple
let barItemCustomFont = UIFont(name: "", size: 14) //note we're not forcing anything here
//can we use our custom font
if let customFont = barItemCustomFont {
//hooray we can use our font
textAttributes = [NSForegroundColorAttributeName: fontColor, NSFontAttributeName: customFont]
} else {
// not found -> omit setting font name and proceed with system font
textAttributes = [NSForegroundColorAttributeName: fontColor]
}
//finally
UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, for: .normal)
Real world example
真实世界的例子
In a real app you would usually need to customize both UINavigationBar
and UIBarButton
font style (aside from other parameters) to make them visually consistent.
Here is handy stylizeNavigationFontOfMyAmazingApp
function you can use:
在实际的应用程序,你通常会需要同时定制UINavigationBar
和UIBarButton
字体样式(除了其他参数),使其在视觉上是一致的。这是stylizeNavigationFontOfMyAmazingApp
您可以使用的方便功能:
func stylizeNavigationFontOfMyAmazingApp() {
//custom font
let customFont = UIFont(name: "someFancyFont", size: 16)! //note we're force unwrapping here
//navigation bar coloring:
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor.blue
//unique text style:
var fontAttributes: [String: Any]
fontAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: customFont]
//navigation bar & navigation buttons font style:
UINavigationBar.appearance().titleTextAttributes = fontAttributes
UIBarButtonItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
}
}
Advantages of using appearance()
proxy
使用appearance()
代理的优点
- Two liner code snippet for stylizing every
UIBarButtonItem
in your app/project. - You can mix
appearance()
proxies of several classes to get truly unique visual style - If you need further customization control you can re-customize each button further (e.g. placing custom views, button, images, etc) - on specific instance of
UIBarButtonItem
.
- 两个 liner 代码片段,用于对您的应用程序/项目中的每一个进行风格化
UIBarButtonItem
。 - 您可以混合
appearance()
多个类的代理以获得真正独特的视觉风格 - 如果您需要进一步的自定义控制,您可以进一步重新自定义每个按钮(例如放置自定义视图、按钮、图像等) - 在
UIBarButtonItem
.
Reference
参考
Apple Docson appearance
protocol.
关于appearance
协议的Apple 文档。
回答by Milad Faridnia
If you want to apply this change to all of your application you can use below code:
如果您想将此更改应用于所有应用程序,您可以使用以下代码:
Swift 4
斯威夫特 4
I've added these lines to AppDelegate.swift
in application
function :
我已经添加了这些行AppDelegate.swift
的application
功能:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().titleTextAttributes = [
NSAttributedStringKey.font: UIFont(name: "IranSansMobile", size: 20)!
]
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "IranSansMobile", size: 15)!], for: UIControlState.normal)
return true
}
Swift 3
斯威夫特 3
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName: UIFont(name: "IranSansMobile", size: 20)!
]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "IranSansMobile", size: 15)!], for: UIControlState.normal)
return true
}
回答by Sergey Gamayunov
For iOS 13, Swift 5.1:
对于 iOS 13、Swift 5.1:
let fontAttr = [NSAttributedString.Key.font: \*your font*\]
let buttonAppearance = UIBarButtonItemAppearance()
buttonAppearance.normal.titleTextAttributes = fontAttr
let navbarAppearance = UINavigationBarAppearance()
navbarAppearance.buttonAppearance = buttonAppearance
UINavigationBar.appearance().standardAppearance = navbarAppearance
回答by borchero
When you are sure you've already set a UIBarButtonItem
you can do:
当您确定已经设置了 a 时,UIBarButtonItem
您可以执行以下操作:
self.navigationItem.leftBarButtonItem!.title = "myTitle"
To change e.g. the color you can do the following:
要更改例如颜色,您可以执行以下操作:
self.navigationItem.leftBarButtonItem!.tintColor = UIColor.redColor()
When you haven't set it in your storyboard you can do:
当您尚未在故事板中设置它时,您可以执行以下操作:
self.navigationItem.leftBarButtonItem = UIBarButtonItem()
For changing the font, do the following:
要更改字体,请执行以下操作:
self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "FONTNAME", size: 20)!], forState: .Normal)
Maybe I should mention that you mustn't use self.navigationController
because when setting the navigationController's buttons they aren't displayed on the screen so as a result the buttons which are on the screen and had been set in the storyboard have to be self.navigationItem
...
也许我应该提一下,你不能使用 self. navigationController
因为在设置导航控制器的按钮时,它们不会显示在屏幕上,因此屏幕上并已在故事板中设置的按钮必须self.navigationItem
...
回答by Ahmed Safadi
SWIFT 3
斯威夫特 3
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Open Sans", size: 15)!,NSForegroundColorAttributeName: UIColor.white]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Open Sans", size: 15)!], for: UIControlState.normal)