简体   繁体   中英

How to change UIButton attributed text colour programatically?

I have a subclass (KeyButton) of UIButton where I am applying certain styles for the button. The following code adds the attributed text for buttons in the ViewController.

func superScriptText(text: String, button: KeyButton, fontSize: Int) {
    let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
    let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
    let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!])
    attString.setAttributes([.font:fontSuper!,.baselineOffset:15], range: NSRange(location:1,length:1))
    button.setAttributedTitle(attString, for: .normal)
}

How can I change the color of attributed text for the button in the class?

Just change:

let attString:NSMutableAttributedString = 
     NSMutableAttributedString(string: text, attributes: [.font:font!])

to:

let attString:NSMutableAttributedString = 
     NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: UIColor.red])

NSAttributedStringKey.foregroundColor is used for the text color, see more options in docs .

You have to add the .foregroundColor key with a UIColor object as the value to the NSAttributedString s attributes dictionary.

Example (assuming you have added a custom button in storyboard):

class CustomButton: UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()

        let text = "CustomButton"

        let font = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
        let textColor = UIColor.orange

        let attributes: [NSAttributedStringKey: Any] = [
            .font: font,
            .foregroundColor: textColor
        ]

        let attributedText = NSAttributedString(string: text, attributes: attributes)
        self.setAttributedTitle(attributedText, for: .normal)
    }
}

I couldn't do this through UIButton subclass. I created the subclass of NSAttributtedText and add the following method:

var textColor: UIColor?

func setSuperScript(text: String, button: KeyButton, fontSize: Int) {
    let font:UIFont? = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.light)
    let fontSuper:UIFont? = UIFont(name: "Helvetica", size:CGFloat(fontSize))
    let attString:NSMutableAttributedString = NSMutableAttributedString(string: text, attributes: [.font:font!, .foregroundColor: textColor!])
    attString.setAttributes([.font:fontSuper!,.baselineOffset:15, .foregroundColor: textColor!,], range: NSRange(location:1,length:1))
    button.setAttributedTitle(attString, for: .normal)
}

I am setting the color based on the logic I have and then set the attributed string color accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM