Change the color of text in this custom navigation bar with two rows?

人盡茶涼 提交于 2019-12-11 17:35:40

问题


I currently have a navigation bar with large titles enabled that also supports two rows with the following code in the 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()

How can I change the font and color of the text in each row of self.title = “This is a Test\n\(result)"

For instance, make "This is a Test" Black and "(result)" gray.


回答1:


Create an attributedString first from the string and add the required attributes, i.e.

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)
}

Create a UILabel and add this attributedString as attributedText of the label.

let label = UILabel()
label.textAlignment = .center
label.numberOfLines = 0
label.attributedText = attributedString

Add this label as the titleView of the navigationItem, i.e.

self.navigationItem.titleView = label


来源:https://stackoverflow.com/questions/56569515/change-the-color-of-text-in-this-custom-navigation-bar-with-two-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!