我知道可以将属性应用于NSAttributedString。
但是我们如何将不同的属性应用于相同的属性字符串。
表示字符串“这是一个属性文本。”
我们如何将特定属性(背景颜色或前景色)设置为“这是” 另一个属性(背景颜色或前景色)到“属性文本”。
有没有办法实现这个目标......?
还有什么方法可以在iOS中设置NSAttributedString的背景颜色吗?
答案 0 :(得分:4)
制作属性字符串的可变副本,然后使用:
-setAttributes:range:
-addAttributes:range:
-addAttribute:value:range:
-removeAttributes:范围:
例如,为前四个字母设置红色:
NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];
在iOS上没有内置的方法来绘制背景颜色。您可以为属性创建自定义字符串常量,例如“MyBackgroundColorAttributeName”,然后您必须自己绘制它。
答案 1 :(得分:2)
我正在使用以下扩展名来更改“NSMutableAttributedString”颜色,并且它很好地完成了这项工作。它可以用作模板
extension NSMutableAttributedString {
func changeColourOf(_ terms: [String], toThisColour termsColour: UIColor,
andForegroundColour fontColour: UIColor) {
// Set your foreground Here
addAttributes([NSAttributedString.Key.foregroundColor : fontColour],
range: NSMakeRange(0, self.length))
// Convert "NSMutableAttributedString" to a NSString
let string = self.string as NSString
// Create a for loop for ther terms array
for term in terms {
// This will be the range of each term
let underlineRange = string.range(of: term)
// Finally change the term colour
addAttribute(NSAttributedString.Key.foregroundColor,
value: termsColour,
range: underlineRange)
}
}
}
示例:
let someMutableStr = NSMutableAttributedString(string: "Hello World 2017 !")
someMutableStr.changeColourOf(["Hello", "2017"],
toThisColour: .blue,
theStringFontColour: .red)