更改此自定义导航栏中两行文本的颜色吗?

时间:2019-06-12 19:54:18

标签: swift uinavigationbar

我目前有一个启用了大标题的导航栏,它在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 个答案:

答案 0 :(得分:0)

首先从attributedString创建一个string,然后添加所需的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的{​​{1}}。

label

将此let label = UILabel() label.textAlignment = .center label.numberOfLines = 0 label.attributedText = attributedString 添加为label的{​​{1}},即

titleView