【问题标题】:Change UILabel attributed String更改 UILabel 属性字符串
【发布时间】:2017-08-21 22:13:47
【问题描述】:

我使用此代码将属性字符串添加到标签:

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

现在是否可以只更改属性字符串 myLabel 的文本并保留属性?

【问题讨论】:

  • 是的,这是可能的。但是你必须通过属性字符串来做。
  • 据我所知。没有。每次标签集属性文本也带有属性字典。如果您想将之前的属性设为函数或地球变量。

标签: ios swift nsattributedstring


【解决方案1】:

通过 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")

注意:只有第一个属性将应用于更新的文本。

【讨论】:

    【解决方案2】:

    更改属性字符串的可变字符串并将 NSMutableAttributedString 重新分配给您的标签。

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

    附言 如果您无权访问您的属性字符串变量,请从标签中获取它。

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

    【讨论】:

      【解决方案3】:

      获取你的标签属性

      let linkAttributes = NSMutableAttributedString(attributedString: label.attributedText)
      

      你可以给add属性。

      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 
      

      【讨论】:

      • 这如何回答 OP 的问题?您没有展示如何在不更改属性的情况下更改属性字符串的字符串属性...
      • 你可以获取标签属性并更改任何一个
      • let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText) 使用 newAttributedString 编辑任何属性
      • 可能在您的答案中包含相关代码,而不是 cmets。
      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2019-09-22
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多