Search code examples
iosswiftuikituibarbuttonitem

UIBarButtonItem text two colours


i'm trying to find solution to change my UIBarButTonItem text in two colours , i find some functions for UILabel, i change it by my task:

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

But I can't really find solution to change UIBarButtonItem to looks like this : Here is image of what I want


Solution

  • Set your button and attributes under your controller class like this:

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

    To change color of single word, simply change relative foregroundColor

    After that in viewDidLoad call your navBar custom button like that:

    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: myButton)
    

    and this is the result

    enter image description here