簡體   English   中英

如何在目標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.

您可以刪除以前的顏色(紅色),然后應用新的顏色,但是由於沒有唯一性,因此它將替換它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM