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

时间:2017-12-14 14:16:02

标签: ios uinavigationcontroller uinavigationbar

我只想自定义导航栏标题的特定部分。

例如,“导航栏标题”。我把这句话作了一个标题。

在“导航”的情况下,应用蓝色和系统粗体字体, 对于“酒吧标题”。我想应用红色和系统常规字体。

怎么可能?

2 个答案:

答案 0 :(得分:2)

您应该使用带有属性标题的UILabel作为导航栏的自定义标题视图。

let titleLabel = UILabel()

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

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

//initializing the attributed string and appending the two parts together
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

//finding the bounds of the attributed text and resizing the label accordingly
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
titleLabel.frame.size = attrString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil).size

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

<强>结果:

navigation bar with custom title view

答案 1 :(得分:0)

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