简体   繁体   English

iOS更改导航栏标题字体和颜色

[英]iOS change navigation bar title font and color

So i have this code that should change the nav bar title font, but it doenst 所以我有这个代码应该更改导航栏标题字体,但它是doenst

    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont
                                                                       fontWithName:_dataManager.optionsSettings.fontString size:14], NSFontAttributeName,
                            [UIColor whiteColor], NSForegroundColorAttributeName, nil];

[[UINavigationBar appearance] setTitleTextAttributes:attributes];

Changing the back button font with this code works just fine. 使用此代码更改后退按钮字体可以正常工作。

   //set backbutton font
NSDictionary *normalAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [UIFont fontWithName:_dataManager.optionsSettings.fontString size:15], NSFontAttributeName,
                                  nil];
[[UIBarButtonItem appearance] setTitleTextAttributes:normalAttributes
                                            forState:UIControlStateNormal];

The correct way to change the title font (and color) is: 更改标题字体(和颜色)的正确方法是:

[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont fontWithName:@"mplus-1c-regular" size:21]}];

Edit: Swift 4.2 编辑:Swift 4.2

self.navigationController?.navigationBar.titleTextAttributes =
[NSAttributedString.Key.foregroundColor: UIColor.red,
 NSAttributedString.Key.font: UIFont(name: "mplus-1c-regular", size: 21)!]

Edit: Swift 4 编辑:斯威夫特4

self.navigationController?.navigationBar.titleTextAttributes =
[NSAttributedStringKey.foregroundColor: UIColor.red,
 NSAttributedStringKey.font: UIFont(name: "mplus-1c-regular", size: 21)!]

Swift 3: 斯威夫特3:

self.navigationController?.navigationBar.titleTextAttributes = 
[NSForegroundColorAttributeName: UIColor.redColor(),
 NSFontAttributeName: UIFont(name: "mplus-1c-regular", size: 21)!]

There is nothing wrong with the other answers. 其他答案没有错。 I'm just sharing the storyboard version for setting the font. 我只是分享故事板版本来设置字体。

1. Select Your Navigation Bar within your Navigation Controller 1.在导航控制器中选择导航栏

导航栏

2. Change the Title Font in the Attributes Inspector 2.在“属性”检查器中更改“标题字体”

标题字体

(You will likely need to toggle the Bar Tint for the Navigation Bar before Xcode picks up the new font) (在Xcode选择新字体之前,您可能需要切换导航栏的Bar Tint)

Notes (Caveats) 笔记(警告)

Verified that this does work on Xcode 7.1.1+. 已经证实这适用于Xcode 7.1.1+。 ( See the Samples below ) 参见下面的样品

  1. You do need to toggle the nav bar tint before the font takes effect (seems like a bug in Xcode; you can switch it back to default and font will stick) 您需要在字体生效之前切换导航栏色调(看起来像Xcode中的错误;您可以将其切换回默认值并且字体会粘住)
  2. If you choose a system font ~ Be sure to make sure the size is not 0.0 (Otherwise the new font will be ignored) 如果选择系统字体〜请务必确保大小不是0.0(否则将忽略新字体)

尺寸

  1. Seems like this works with no problem when only one NavBar is in the view hierarchy. 如果只有一个NavBar在视图层次结构中,这似乎没有问题。 It appears that secondary NavBars in the same stack are ignored. 似乎忽略了同一堆栈中的辅助NavBars。 (Note that if you show the master navigation controller's navBar all the other custom navBar settings are ignored). (请注意,如果显示主导航控制器的navBar,则忽略所有其他自定义navBar设置)。

Gotchas (deux) 陷阱(deux)

Some of these are repeated which means they are very likely worth noting. 其中一些重复,这意味着它们很可能值得注意。

  1. Sometimes the storyboard xml gets corrupt. 有时故事板xml会被破坏。 This requires you to review the structure in Storyboard as Source Code mode (right click the storyboard file > Open As ...) 这需要您将Storyboard中的结构作为源代码模式进行检查(右键单击故事板文件>打开为...)
  2. In some cases the navigationItem tag associated with user defined runtime attribute was set as an xml child of the view tag instead of the view controller tag. 在某些情况下,与用户定义的运行时属性关联的navigationItem标记被设置为视图标记的xml子标记,而不是视图控制器标记。 If so remove it from between the tags for proper operation. 如果是这样,请将其从标签之间移除以便正确操作。
  3. Toggle the NavBar Tint to ensure the custom font is used. 切换导航栏色调以确保使用自定义字体。
  4. Verify the size parameter of the font unless using a dynamic font style 除非使用动态字体样式,否则请验证字体的大小参数
  5. View hierarchy will override the settings. 视图层次结构将覆盖设置。 It appears that one font per stack is possible. 似乎每个堆栈有一种字体是可能的。

Result 结果

导航栏斜体

Samples 样品

Handling Custom Fonts 处理自定义字体

Note ~ A nice checklist can be found from the Code With Chris website and you can see the sample download project. 注意〜可以在Code With Chris网站上找到一个很好的清单 ,你可以看到示例下载项目。

If you have your own font and want to use that in your storyboard, then there is a decent set of answers on the following SO Question . 如果您有自己的字体并希望在故事板中使用它,那么在以下SO问题上有一套不错的答案。 One answer identifies these steps. 一个答案确定了这些步骤。

  1. Get you custom font file(.ttf,.ttc) 获取自定义字体文件(.ttf,.ttc)
  2. Import the font files to your Xcode project 将字体文件导入Xcode项目
  3. In the app-info.plist,add a key named Fonts provided by application.It's an array type , add all your font file names to the array,note:including the file extension. 在app-info.plist中,添加一个由application提供的名为Fonts的键。它是一个数组类型,将所有字体文件名添加到数组中,注意:包括文件扩展名。
  4. In the storyboard , on the NavigationBar go to the Attribute Inspector,click the right icon button of the Font select area.In the popup panel , choose Font to Custom, and choose the Family of you embeded font name. 在故事板中,在NavigationBar上转到“属性”检查器,单击“字体选择”区域的右侧图标按钮。在弹出式面板中,选择“字体到自定义”,然后选择“嵌入字体名称族”。

Custom Font Workaround 自定义字体解决方法

So Xcode naturally looks like it can handle custom fonts on UINavigationItem but that feature is just not updating properly (The font selected is ignored). 所以Xcode自然看起来它可以处理UINavigationItem上的自定义字体,但该功能只是没有正确更新(所选字体被忽略)。

UINavigationItem

To workaround this: 要解决此问题:

One way is to fix using the storyboard and adding a line of code: First add a UIView (UIButton, UILabel, or some other UIView subclass) to the View Controller (Not the Navigation Item...Xcode is not currently allowing one to do that). 一种方法是使用故事板修复并添加一行代码:首先将UIView(UIButton,UILabel或其他一些UIView子类)添加到视图控制器(不是导航项...... Xcode目前不允许进行操作那)。 After you add the control you can modify the font in the storyboard and add a reference as an outlet to your View Controller. 添加控件后,您可以修改故事板中的字体,并将引用添加到View Controller的插座中。 Just assign that view to the UINavigationItem.titleView. 只需将该视图分配给UINavigationItem.titleView即可。 You could also set the text name in code if necessary. 如有必要,您还可以在代码中设置文本名称。 Reported Bug (23600285). 报告错误(23600285)。

@IBOutlet var customFontTitleView: UIButton!

//Sometime later...    
self.navigationItem.titleView = customFontTitleView

Try this: 试试这个:

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [UIColor whiteColor],NSForegroundColorAttributeName,
                                [UIColor whiteColor],NSBackgroundColorAttributeName,nil];
self.navigationController.navigationBar.titleTextAttributes = textAttributes;

My Swift code for change Navigation Bar title: 我的Swift代码更改导航栏标题:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = attributes

And if you want to change background font too then I have this in my AppDelegate: 如果你想改变背景字体,那么我在我的AppDelegate中有这个:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)

Here is an answer for your question: 以下是您的问题的答案:

Move your code to below method because navigation bar title updated after view loaded. 将代码移动到下面的方法,因为导航栏标题在加载视图后更新。 I tried adding above code in viewDidLoad doesn't work, it works fine in viewDidAppear method. 我尝试在viewDidLoad中添加上面的代码不起作用,它在viewDidAppear方法中工作正常。

  -(void)viewDidAppear:(BOOL)animated{}

Anyone needs a Swift 3 version. 任何人都需要Swift 3版本。 redColor() has changed to just red . redColor()已更改为red

self.navigationController?.navigationBar.titleTextAttributes =
        [NSForegroundColorAttributeName: UIColor.red,
         NSFontAttributeName: UIFont(name: "{your-font-name}", size: 21)!]

ADD this single line code in your App Delegate - Did Finish Lauch. 在App Delegate中添加此单行代码 - Did Finish Lauch。 It will change Font, color of navigation bar throughout the application. 它会在整个应用程序中更改字体,导航栏的颜色。

UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "YOUR FONT NAME", size: 25.0)!]

It's a bit more readable using literals: 使用文字更具可读性:

self.navigationController.navigationBar.titleTextAttributes = @{
                                                              NSFontAttributeName:[UIFont fontWithName:@"mplus-1c-regular" size:21],
                                                              NSForegroundColorAttributeName: [UIColor whiteColor]
                                                              };

I had one problem because when I tried to change my NavigationItem title programmatically i was not able to find my family font (tried many things but impossible to make it run correctly) so I found one workaround very nice and easy in storyboard. 我遇到了一个问题,因为当我尝试以编程方式更改我的NavigationItem标题时,我无法找到我的家族字体(尝试了很多东西,但不可能让它正常运行)所以我发现一个解决方法非常好用且简单易用。

  1. Firstly you add under Navigation Item one view in middle and don't forget to set backGroundColor to clear color to have the same color of navBar: 首先,在“导航项目”中添加一个视图,并且不要忘记设置backGroundColor以清除颜色以使其具有相同颜色的navBar:

在此输入图像描述

  1. Then you add one Label which you can edit (set color of text, font, size...) in this view 然后在此视图中添加一个可以编辑的标签(设置文本颜色,字体,大小......)
  2. You add constraints to label (Top = 0, Bottom = 0, Trailing = 0 and Leading = 0) to View and center text of label 您将标签(Top = 0,Bottom = 0,Trailing = 0和Leading = 0)的约束添加到标签的视图和中心文本

Finally you should have something like that in document outline: 最后你应该在文档大纲中有类似的东西:

在此输入图像描述

And something like that in your ViewController: 在ViewController中有类似的东西:

在此输入图像描述

Hope it can help. 希望它可以提供帮助。

迅速:-

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Love Nature", size: 40)!]

This one for alternative to Swift 4 (already answer by @Josh): 这个替代Swift 4(已经由@Josh回答):

let titleTextAttributed: [NSAttributedStringKey: Any] = [.foregroundColor: UIColor.red, .font: UIFont(name: "AvenirNext-Regular", size: 20) as Any]
navigationController?.navigationBar.titleTextAttributes = titleTextAttributed

iOS 11 iOS 11

在此输入图像描述

Objective-C Objective-C的

if (@available(iOS 11.0, *)) {
    self.navigationController.navigationItem.largeTitleDisplayMode =  UINavigationItemLargeTitleDisplayModeAlways;
    self.navigationController.navigationBar.prefersLargeTitles = true;

// Change Color
    self.navigationController.navigationBar.largeTitleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};

} else {
    // Fallback on earlier versions
}

For Objective-C to set Font and Color 对于Objective-C来设置字体和颜色

- (void)_setup {
    NSDictionary *barButtonTitleAttributes = @{
                                               NSForegroundColorAttributeName : [UIColor whiteColor],
                                               NSFontAttributeName :[UIFont fontWithName:@"Lato-Regular" size:15.0]
                                               };
    [self.navigationBar setTitleTextAttributes:barButtonTitleAttributes];

}

Here is an answer for Swift 4 😁: 以下是Swift 4的答案:

    let textAttributes:[String:Any]? = [NSAttributedStringKey.foregroundColor.rawValue:UIColor.blue, NSAttributedStringKey.font.rawValue:UIFont(name:"Avenir Next", size:20)!]
    navigationController?.navigationBar.titleTextAttributes = textAttributes

Don't forget to add the Raw values of the keys to avoid compile errors. 不要忘记添加键的Raw值以避免编译错误。

    let textAttributes:[NSAttributedStringKey: Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue):UIColor.blue, NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):UIFont(name:"OpenSans", size: 17)!]
    navigationController?.navigationBar.titleTextAttributes = textAttributes

Swift 4.2 Swift 4.2

self.navigationController?.navigationBar.titleTextAttributes =
        [NSAttributedString.Key.foregroundColor: UIColor.white,
         NSAttributedString.Key.font: UIFont(name: "LemonMilklight", size: 21)!]

Add this extension 添加此扩展程序

extension UINavigationBar {
    func changeFont() {
        self.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Poppins-Medium", size: 17)!]
    }
}

Add the following line in viewDidLoad() 在viewDidLoad()中添加以下行

self.navigationController?.navigationBar.changeFont()

Working in swift 3.0 For changing the title color you need to add titleTextAttributes like this 在swift 3.0中工作要更改标题颜色,您需要像这样添加titleTextAttributes

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

For changing navigationBar background color you can use this
        self.navigationController.navigationBar.barTintColor = UIColor.white

For changing navigationBar back title and back arrow color you can use this
       self.navigationController.navigationBar.tintColor = UIColor.white

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM