setting NSAttributed String attribute overrides substring attributes

偶尔善良 提交于 2020-01-23 10:36:30

问题


I have created a mutable string which will look like @"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)];

When I add Attribute foregroundColor , the existing green color in substring gets overridden by the specified black color. Though I can change the code to set the green color for substring, I would like to know is there any other way of applying styles to the part of Strings which doesn't have styles without overriding the existing styles.


回答1:


You can enumerate over each attribute span in the string, and only change attributes if they are not already set

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



来源:https://stackoverflow.com/questions/15927143/setting-nsattributed-string-attribute-overrides-substring-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!