UINavigationBar中如何自定义导航栏标题字体和大小?
How to customize navigation bar title font and size in UINavigationBar?
我只想自定义导航栏标题的特定部分。
比如"Navigation Bar Title."我把这句话当标题
在"Navigation"的情况下,应用蓝色和系统粗体字体,
对于 "Bar Title." 我想应用红色和系统常规字体。
怎么可能?
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];
您应该使用带有属性标题的 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
结果:
我只想自定义导航栏标题的特定部分。
比如"Navigation Bar Title."我把这句话当标题
在"Navigation"的情况下,应用蓝色和系统粗体字体, 对于 "Bar Title." 我想应用红色和系统常规字体。
怎么可能?
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];
您应该使用带有属性标题的 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
结果: