Swift 为UINavigationController标题中的单个单词设置字体
我有一个Swift 为UINavigationController标题中的单个单词设置字体,swift,uinavigationcontroller,nsattributedstring,Swift,Uinavigationcontroller,Nsattributedstring,我有一个UINavigationController设置为prefersLargeTitles=true 我想设置标题,以便 Discogs|搜索框 上面写着 Discogs|搜索框 但是,我看不到如何通过属性文本设置文本 这可能吗我正在以编程方式构建视图 我看到一个navigationController?.navigationBar.largeTitleTextAttributes属性,但由于它只接受键/值对,我认为这不能用于应用此效果。对于大标题: 可以创建自定义视图(带有标题标签)并将
UINavigationController
设置为prefersLargeTitles=true
我想设置标题,以便
Discogs|搜索框
上面写着
Discogs|搜索框
但是,我看不到如何通过属性文本设置文本
这可能吗我正在以编程方式构建视图
我看到一个
navigationController?.navigationBar.largeTitleTextAttributes
属性,但由于它只接受键/值对,我认为这不能用于应用此效果。对于大标题:
可以创建自定义视图(带有标题标签)并将约束设置为导航栏:
customView.widthAnchor.constraint(equalToConstant: 200).isActive = true
customView.heightAnchor.constraint(equalToConstant: 44).isActive = true
self.navigationItem.titleView = customView
对于常规标题: 您可以将自定义标签设置为navigationItem的标题视图:
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
来源:
这是一个很好的解决方案,可以回答这个问题。我还建议OP阅读这个答案中给出的更改字体的封装(通过
ChangableFont
协议):。我认为这很好地补充了您简洁的回答。感谢您的输入,我尝试过这种方法,但是当preferslargetilles
为true
时,它似乎不起作用。似乎没有一个干净的解决方案: