如何在 objective c 中替换属性字符串中的颜色
how to Replace color in attributed string in objective c
在我的属性字符串中有多种颜色。像红色、黑色、绿色
这里是示例字符串
在此字符串中,我想将所有红色单词替换为黄色。
任何人都可以指导我如何实现这个目标吗?
谢谢。
您需要枚举 NSAttributedString 并在满足条件时更改属性的值。
文本颜色属性由 NSForegroundColorAttributeName
完成。
attr
就是你对应的NSMutableAttributedString
//Retrieve the current attributedText. You need to make it mutable.
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:yourLabelOrTextView.attributedText];
[attr enumerateAttribute:NSForegroundColorAttributeName
inRange:NSMakeRange(0, [attr length]) options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if ([value isKindOfClass:[UIColor class]]) //Check just in case that the value is really a UIColor
{
UIColor *currentColor = (UIColor *)value;
if ([currentColor isEqual:[UIColor redColor]]) //Condition
{
[attr addAttribute:NSForegroundColorAttributeName
value:[UIColor yellowColor]
range:range];
}
}
}];
[yourLabelOrTextView setAttributedText:attr]; //Replace the previous attributedText on UI with the new one.
您可以删除以前的颜色(红色),然后应用新的颜色,但由于您不必这样做,它会替换它。
在我的属性字符串中有多种颜色。像红色、黑色、绿色
这里是示例字符串
在此字符串中,我想将所有红色单词替换为黄色。
任何人都可以指导我如何实现这个目标吗?
谢谢。
您需要枚举 NSAttributedString 并在满足条件时更改属性的值。
文本颜色属性由 NSForegroundColorAttributeName
完成。
attr
就是你对应的NSMutableAttributedString
//Retrieve the current attributedText. You need to make it mutable.
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:yourLabelOrTextView.attributedText];
[attr enumerateAttribute:NSForegroundColorAttributeName
inRange:NSMakeRange(0, [attr length]) options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if ([value isKindOfClass:[UIColor class]]) //Check just in case that the value is really a UIColor
{
UIColor *currentColor = (UIColor *)value;
if ([currentColor isEqual:[UIColor redColor]]) //Condition
{
[attr addAttribute:NSForegroundColorAttributeName
value:[UIColor yellowColor]
range:range];
}
}
}];
[yourLabelOrTextView setAttributedText:attr]; //Replace the previous attributedText on UI with the new one.
您可以删除以前的颜色(红色),然后应用新的颜色,但由于您不必这样做,它会替换它。