【问题标题】:Attributed text swift how to change color of unattributed text属性文本快速如何更改未属性文本的颜色
【发布时间】:2016-08-26 13:46:44
【问题描述】:

我尝试为我的应用设置夜间/白天选项。我有一个像 "<font color="#aa2c2c">Red text</font>then back to normal " 这样的文本。 所以我需要红色来保持红色并且只改变未归属的颜色。

这是我的尝试:

    text.enumerateAttributesInRange(NSRange(0..<text.length), options: []) { (attributes, range, _) -> Void in
        for (attribute, object) in attributes {
            NSLog("attr \(attribute) object \(object)")                
            }
        }
    }

所以,日志显示了类似“attr NSColor object UIDeviceRGBColorSpace 0 0 0 1”或“attr NSStrokeColor object UIDeviceRGBColorSpace 0 0 0 1”的内容。那似乎是我需要将其更改为白色的黑色文本。

所以我把它放在循环中:

        if object.name!.containsString("0 0 0 1"){
            text.setAttributes(NSForegroundColorAttributeName, value: UIColor.whiteColor() , range: range)
        }

我不确定这是否是最好的决定,但我得到了错误:调用中的额外参数“值”。 这有什么问题?仅替换非归属文本颜色的最佳方法是什么?

【问题讨论】:

  • 没有NSMutableAttributeString setAttributes:value:range:这样的方法。有setAttributes:range:addAttribute:value:range:,或addAttributes:range:
  • 不要用对象的描述来比较,值应该是UIColor,直接比较就行了。

标签: ios swift nsmutableattributedstring


【解决方案1】:
 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
 let linkTextWithColor = "click here"

 let range = (text as NSString).rangeOfString(linkTextWithColor)

 let attributedString = NSMutableAttributedString(string:text)
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

 self.helpText.attributedText = attributedString

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多