[英]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.
您可以刪除以前的顏色(紅色),然后應用新的顏色,但是由於沒有唯一性,因此它將替換它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.