gpt4 book ai didi

objective-c - 设置 NSAttributed 字符串属性覆盖子字符串属性

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:57 25 4
gpt4 key购买 nike

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

最佳答案

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

 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

关于objective-c - 设置 NSAttributed 字符串属性覆盖子字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com