如何以编程方式更改UIButton属性文本颜色?

时间:2018-01-28 14:17:23

标签: ios swift uibutton

我有一个UIButton的子类(KeyButton),我正在为按钮应用某些样式。以下代码在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)
}

如何更改班级按钮的属性文本颜色?

3 个答案:

答案 0 :(得分:1)

只需改变:

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

为:

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

NSAttributedStringKey.foregroundColor用于文字颜色,请参阅docs中的更多选项。

答案 1 :(得分:0)

您必须将.foregroundColor密钥与UIColor对象一起添加为NSAttributedString s attributes字典的值。

示例(假设您在故事板中添加了自定义按钮):

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

答案 2 :(得分:0)

我不能通过UIButton子类来做到这一点。我创建了NSAttributtedText的子类并添加了以下方法:

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

我根据我的逻辑设置颜色,然后相应地设置属性字符串颜色。