UIBarButtonItem 文本两种颜色

UIBarButtonItem text two colours

我正在尝试寻找解决方案,以两种颜色更改我的 UIBarButTonItem 文本,我找到了 UILabel 的一些功能,我通过我的任务更改它:

extension NSMutableAttributedString {
    func setColorForText(textForAttribute: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
        self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
    }
}
extension UILabel{
    func setTwoColors(firstWord: String, secondWord: String , firstColor:UIColor = .white , secondColor: UIColor = .blue) {
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: firstWord+secondWord)
        attributedString.setColorForText(textForAttribute: firstWord, withColor: firstColor)
        attributedString.setColorForText(textForAttribute: secondWord, withColor: secondColor)
        self.attributedText = attributedString
    }
}

但我真的找不到将 UIBarButtonItem 更改为如下所示的解决方案: Here is image of what I want

像这样在控制器下设置按钮和属性 class:

let myButton: UIButton = {
    let b = UIButton()
    let attributedString = NSMutableAttributedString(string: "Label 1", attributes: [.foregroundColor: UIColor.yellow, .font: UIFont.systemFont(ofSize: 16, weight: .semibold)]) // first word
    attributedString.append(NSAttributedString(string: " - ", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 16, weight: .semibold)])) // intermediate
    attributedString.append(NSAttributedString(string: "Label 2", attributes: [.foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 16, weight: .semibold)])) // second word
    b.setAttributedTitle(attributedString, for: .normal)
    
    return b
}()

要改变单个单词的颜色,只需改变相对的前景色

之后在 viewDidLoad 中调用你的 navBar 自定义按钮:

navigationItem.leftBarButtonItem = UIBarButtonItem(customView: myButton)

这是结果