簡體   English   中英

更改UILabel屬性String

[英]Change UILabel attributed String

我使用此代碼將屬性字符串添加到標簽:

let attrString = NSMutableAttributedString(string: text)
// add some attributes
myLabel.attributedText = attrString

現在是否可以僅更改屬性字符串myLabel的文本並保留屬性?

通過它的mutableString屬性

例:

let astrMessage = NSMutableAttributedString(string: "Hello World")

//set some attributes
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                         value: UIColor.blue,
                         range: NSRange(location: 0, length: 5))
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor,
                         value: UIColor.red,
                         range: NSRange(location: 6, length: 5))

//update
astrMessage.mutableString.setString("World Welcome")

注意:只有第一個屬性將應用於更新的文本。

獲取您的標簽屬性

let linkAttributes = NSMutableAttributedString(attributedString: label.attributedText)

你可以給添加屬性。

linkAttributes.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: linkRange)
let linkAttributes: [String : Any] = [
    NSForegroundColorAttributeName: UIColor.green,
    NSUnderlineColorAttributeName: UIColor.lightGray,
    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]

將歸屬文本添加到標簽中

myLabel.attributedText = linkAttributes 

更改屬性字符串的可變字符串,並將NSMutableAttributedString重新分配給您的標簽。

attrString.mutableString.setString("newText")
myLabel.attributedText = attrString

PS如果您無法訪問屬性字符串變量,請從標簽中獲取。

let myAttrString = myLabel.attributedText as? NSMutableAttributedString
if let attrString = myAttrString {
    attrString.mutableString.setString("newText")
    myLabel.attributedText = attrString
}

暫無
暫無

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

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