设置NSAttributed String属性会覆盖子字符串属性

时间:2013-04-10 13:24:07

标签: objective-c nsattributedstring

我创建了一个可变字符串,看起来像@“ testMeIn:greenColor:Different:greencolor:Colors

NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:myString];

UIColor *foregroundColor = [UIColor blackColor];
NSString *key = NSForegroundColorAttributeName;

[mutableText addAttribute:key value:foregroundColor range:NSMakeRange(0, myString.length)];

当我添加属性foregroundColor时,子串中的现有绿色将被指定的黑色覆盖。虽然我可以更改代码来设置子字符串的绿色,但我想知道是否有任何其他方式将样式应用于字符串的部分,没有样式而不覆盖现有样式。

1 个答案:

答案 0 :(得分:4)

您可以枚举字符串中的每个属性范围,只有在尚未设置的情况下才更改属性

 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];
     }];

enter image description here