用两行更改此自定义导航栏中的文本颜色?
Posted
技术标签:
【中文标题】用两行更改此自定义导航栏中的文本颜色?【英文标题】:Change the color of text in this custom navigation bar with two rows? 【发布时间】:2019-06-12 19:54:18 【问题描述】:我目前有一个启用大标题的导航栏,它还支持两行,在 viewdidLoad 中有以下代码:
navigationController?.navigationBar.prefersLargeTitles = true
self.navigationController?.navigationItem.largeTitleDisplayMode = .automatic
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd"
let result = formatter.string(from: date)
self.title = “This is a Test\n\(result)"
var count = 0
for item in(self.navigationController?.navigationBar.subviews)!
for sub in item.subviews
if sub is UILabel
if count == 1
break;
let titleLab :UILabel = sub as! UILabel
titleLab.numberOfLines = 0
titleLab.text = self.title
titleLab.lineBreakMode = .byWordWrapping
count = count + 1
self.navigationController?.navigationBar.layoutSubviews()
self.navigationController?.navigationBar.layoutIfNeeded()
如何更改每行文本的字体和颜色
self.title = “This is a Test\n\(result)"
例如,将"This is a Test"
设为黑色和"(result)"
设为灰色。
【问题讨论】:
【参考方案1】:首先从string
创建一个attributedString
并添加所需的attributes
,即
let result = "13 June 2019"
let text = "This is a Test\n\(result)"
let arr = text.components(separatedBy: .newlines)
let attributedString = NSMutableAttributedString()
for (index, str) in arr.enumerated()
let attrStr = NSMutableAttributedString(string: str)
if index == 0
attrStr.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: str.count))
attrStr.addAttribute(.font, value: UIFont.systemFont(ofSize: 12.0, weight: .bold), range: NSRange(location: 0, length: str.count))
else
attrStr.addAttribute(.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: str.count))
attrStr.addAttribute(.font, value: UIFont.systemFont(ofSize: 12.0), range: NSRange(location: 0, length: str.count))
if index < arr.count
attributedString.append(NSAttributedString(string: "\n"))
attributedString.append(attrStr)
创建一个UILabel
并将此attributedString
添加为attributedText
的label
。
let label = UILabel()
label.textAlignment = .center
label.numberOfLines = 0
label.attributedText = attributedString
将此label
添加为titleView
的navigationItem
,即
self.navigationItem.titleView = label
【讨论】:
这个答案真的帮了我很多,我真的很感激。你介意看看这个吗?类似,***.com/q/56613252/11349745以上是关于用两行更改此自定义导航栏中的文本颜色?的主要内容,如果未能解决你的问题,请参考以下文章