簡體   English   中英

如何以編程方式更改UIButton屬性文本的顏色?

[英]How to change UIButton attributed text colour programatically?

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

如何更改類中按鈕的屬性文本的顏色?

只是改變:

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

至:

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

NSAttributedStringKey.foregroundColor用於文本顏色,請參閱docs中的更多選項。

您必須將帶有UIColor對象的.foregroundColor鍵添加為NSAttributedStringattributes字典的值。

示例(假設您已在情節提要中添加了自定義按鈕):

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

我無法通過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)
}

我根據已有的邏輯設置顏色,然后相應地設置屬性字符串的顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM