我创建了一个可变字符串,看起来像@”测试 MeIn:绿色 颜色:不同:绿色 颜色:颜色"
NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:myString];
UIColor *foregroundColor = [UIColor blackColor];
NSString *key = NSForegroundColorAttributeName;
[mutableText addAttribute:key value:foregroundColor range:NSMakeRange(0, myString.length)];
当我添加属性 foregroundColor 时,子字符串中现有的绿色将被指定的黑色覆盖。虽然我可以更改代码来设置子字符串的绿色,但我想知道是否有其他方法可以将样式应用于没有样式的字符串部分而不覆盖现有样式。
您可以枚举字符串中的每个属性范围,并且仅更改尚未设置的属性
NSMutableAttributedString* aString =
[[NSMutableAttributedString alloc] initWithString:@"testMeIn DIFFERENT Colors"];
[aString setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}
range:(NSRange){9,9}];
[aString enumerateAttributesInRange:(NSRange){0,aString.length}
options:nil
usingBlock:
^(NSDictionary* attrs, NSRange range, BOOL *stop) {
//unspecific: don't change text color if ANY attributes are set
if ([[attrs allKeys] count]==0)
[aString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:range];
//specific: don't change text color if text color attribute is already set
if (![[attrs allKeys] containsObject:NSForegroundColorAttributeName])
[aString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:range];
}];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)