【问题标题】:setting NSAttributed String attribute overrides substring attributes设置 NSAttributed String 属性覆盖子字符串属性
【发布时间】:2013-04-10 13:24:06
【问题描述】:

我创建了一个可变字符串,看起来像 @"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 时,子字符串中现有的绿色会被指定的黑色覆盖。虽然我可以更改代码以设置子字符串的绿色,但我想知道是否有任何其他方法可以将样式应用于没有样式而不覆盖现有样式的字符串部分。

【问题讨论】:

    标签: objective-c nsattributedstring


    【解决方案1】:

    您可以枚举字符串中的每个属性跨度,并且仅在尚未设置属性时更改属性

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

    【讨论】:

    • 谢谢,这应该可以。但恐怕,当样式频繁更换时,它可能会成为一项代价高昂的操作。并且不同的样式被添加到一个冗长的字符串中。
    猜你喜欢
    • 2011-05-13
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2017-08-29
    • 2015-11-01
    相关资源
    最近更新 更多