我知道可以将属性应用于 NSAttributedString。
但是我们如何将不同的属性应用于相同的属性字符串。
对于字符串“这是一个属性文本”。
我们如何将特定属性(背景颜色或前景色)设置为“这是”另一个属性(背景颜色或前景色)设置为“属性文本”。
有没有办法实现这一目标......?
还有什么方法可以在 iOS 中设置 NSAttributedString 的背景颜色?
我知道可以将属性应用于 NSAttributedString。
但是我们如何将不同的属性应用于相同的属性字符串。
对于字符串“这是一个属性文本”。
我们如何将特定属性(背景颜色或前景色)设置为“这是”另一个属性(背景颜色或前景色)设置为“属性文本”。
有没有办法实现这一目标......?
还有什么方法可以在 iOS 中设置 NSAttributedString 的背景颜色?
制作属性字符串的可变副本,然后使用:
-setAttributes:范围:
-addAttributes:范围:
-addAttribute:值:范围:
-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”,然后您必须自己绘制它。
我正在使用以下扩展来更改“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)
编辑 2021
extension NSMutableAttributedString
{
func colourTerms(_ terms:[String] = [],
withColour colour:UIColor = .blue,
onforegroundColour foregroundColour:UIColor = .white)
{
let fontSize:CGFloat = 25
self.addAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize),NSAttributedString.Key.foregroundColor:foregroundColour], range:NSMakeRange(0, self.length) )
let text = self.string
for term in terms
{
let charCount = term.count
var options:NSString.EnumerationOptions = .byWords
switch charCount
{
case 1:
options = .byComposedCharacterSequences
default:
if term.contains(" ")
{
options = .bySentences
}else
{
options = .byWords
}
}
string.enumerateSubstrings(in: text.startIndex..<text.endIndex,
options: options)
{ (subString,substringRange,_,_) in
if subString!.contains(term)
{
self.addAttribute(NSAttributedString.Key.foregroundColor,
value: colour,
range: NSRange(substringRange, in: text))}}}}}
示例 2021
let attrText = NSMutableAttributedString(string: """
Hello World 2021!
Happy 2021
""")
attrText.colourTerms(["Hello","2021"])
//Before this second color will stay the same , now fixed!
//See images below