简体   繁体   English

如何在 UINavigationBar 中自定义导航栏标题字体和大小?

[英]How to customize navigation bar title font and size in UINavigationBar?

I want to customize only a specific part of the navigation bar title.我只想自定义导航栏标题的特定部分。

For example, "Navigation Bar Title."例如,“导航栏标题”。 I made this sentence a title.我把这句话当成了标题。

In the case of "Navigation", apply blue color and system bold font, For "Bar Title."在“导航”的情况下,应用蓝色和系统粗体字体,对于“栏标题”。 I want to apply red color and system regular fonts.我想应用红色和系统常规字体。

How is it possible?这怎么可能?

You should use a UILabel with an attributed title as a custom title view for your navigation bar.您应该使用带有属性标题的UILabel作为导航栏的自定义标题视图。

let titleLabel = UILabel()

//attributes for the first part of the string  
let firstAttr: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 16),
                                                .foregroundColor: UIColor.blue]

//attributes for the second part of the string  
let secondAttr: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 16),
                                                 .foregroundColor: UIColor.red]

//initializing and merging the two parts
let attrString = NSMutableAttributedString(string: "Navigation", attributes: firstAttr)
let secondAttrString = NSAttributedString(string: " Bar Title", attributes: secondAttr)
attrString.append(secondAttrString)

//setting the attributed string as an attributed text
titleLabel.attributedText = attrString

//set the size of the label to fit its contents
titleLabel.sizeToFit()

//setting the label as the title view of the navigation bar
navigationItem.titleView = titleLabel

Result:结果:

带有自定义标题视图的导航栏

try this

NSDictionary *settings = @{
    UITextAttributeFont                 :  [UIFont fontWithName:@"YOURFONTNAME" size:20.0],
    UITextAttributeTextColor            :  [UIColor whiteColor],
    UITextAttributeTextShadowColor      :  [UIColor clearColor],
    UITextAttributeTextShadowOffset     :  [NSValue valueWithUIOffset:UIOffsetZero]};

[[UINavigationBar appearance] setTitleTextAttributes:settings];

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

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