为UINavigationController的标题中的单个单词设置字体

时间:2019-07-03 08:25:45

标签: swift uinavigationcontroller nsattributedstring

我有一个UINavigationController设置的prefersLargeTitles = true

example image

我想设置标题,而不是

Discogs |搜索框

它读取

迪斯科斯 |搜索框

但是我看不到如何通过属性文本设置文本。

这可能吗? 我正在以编程方式构建视图

我看到了一个navigationController?.navigationBar.largeTitleTextAttributes属性,但由于该属性仅接受键/值对,因此我不认为可以将其应用于这种效果。

1 个答案:

答案 0 :(得分:2)

对于大标题:

您可以创建自定义视图(带有标题标签)并将约束设置为导航栏:

customView.widthAnchor.constraint(equalToConstant: 200).isActive = true
customView.heightAnchor.constraint(equalToConstant: 44).isActive = true

self.navigationItem.titleView = customView

常规标题:

您可以将自定义标签设置为navigationItem的titleView:

let navLabel = UILabel()
let navTitle = NSMutableAttributedString(string: "Discogs", attributes:[
    NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17.0),
    NSAttributedStringKey.foregroundColor: UIColor.black])

navTitle.append(NSMutableAttributedString(string: " | Search Box", attributes:[
    NSAttributedStringKey.foregroundColor: UIColor.black,
    NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17.0, weight: 
        UIFont.Weight.light)]))

navLabel.attributedText = navTitle
self.navigationItem.titleView = navLabel

来源:

Dushyant Bansal's Medium Article

相关问题