我尝试为我的应用程序做一个夜/日选项。我有一个像"<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对象UIDeviceRGBColorSpace 0 0 0 1"或"attr NSStrokeColor对象UIDeviceRGBColorSpace 0 0 0 1"的东西。这似乎是黑色的文本,我需要把它变成白色。
所以我把这个放到循环中:
if object.name!.containsString("0 0 0 1"){
text.setAttributes(NSForegroundColorAttributeName, value: UIColor.whiteColor() , range: range)
}
我不确定这是否是最好的决定,但我得到了错误:在调用中额外的参数'值'。这有什么问题,什么是最好的方法来替代非属性文本的颜色?
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))