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

谁说胖子不能爱 提交于 2020-01-11 12:16:29

问题


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?


回答1:


You should use a UILabel with an attributed title as a custom title view for your navigation bar.

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:




回答2:


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];


来源:https://stackoverflow.com/questions/47815476/how-to-customize-navigation-bar-title-font-and-size-in-uinavigationbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!