如何自定义UINavigationBar中的导航栏标题字体和大小? [英] How to customize navigation bar title font and size in UINavigationBar?

查看:320
本文介绍了如何自定义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.

怎么可能?

推荐答案

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

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

结果:

这篇关于如何自定义UINavigationBar中的导航栏标题字体和大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆