2013-04-10 123 views
3

我创建了一个可变的字符串,像@“testMeIn:绿彩:不同:绿彩:颜色设置NSAttributed字符串属性覆盖子属性

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

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

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

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

回答

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

+0

谢谢,这应该工作。 但是,如果风格经常改变,恐怕会变成一个代价高昂的操作。并且在一个冗长的字符串中添加不同的样式。 – Friendtam 2013-04-19 09:56:15