这个问题可能与this one 重复.但答案对我不起作用,我想更具体一些。
我有一个 NSString
,但我需要一个 NS(Mutable)AttributedString
并且这个字符串中的一些单词应该被赋予不同的颜色。我试过这个:
NSString *text = @"This is the text and i want to replace something";
NSDictionary *attributes = @ {NSForegroundColorAttributeName : [UIColor redColor]};
NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] initWithString:@"AND" attributes:attributes];
NSMutableAttributedString *newText = [[NSMutableAttributedString alloc] initWithString:text];
newText = [[newText mutableString] stringByReplacingOccurrencesOfString:@"and" withString:[subString mutableString]];
“and”应该是大写的红色。
文档说 mutableString 保留属性映射。但是随着我的替换,我在分配的右侧不再有 attributedString(在我的代码片段的最后一行)。
我怎样才能得到我想要的? ;)
最佳答案
@Hyperlord 的答案将起作用,但前提是输入字符串中出现一次“and”一词。无论如何,我要做的是使用 NSString 的 stringByReplacingOccurrencesOfString:
最初将每个“and”更改为“AND”,然后使用一点正则表达式来检测属性字符串中的匹配项,并应用 NSForegroundColorAttributeName
在那个范围内。这是一个例子:
NSString *initial = @"This is the text and i want to replace something and stuff and stuff";
NSString *text = [initial stringByReplacingOccurrencesOfString:@"and" withString:@"AND"];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(AND)" options:kNilOptions error:nil];
NSRange range = NSMakeRange(0,text.length);
[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:1];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];
最后,只需将属性字符串应用到您的标签即可。
[myLabel setAttributedText:mutableAttributedString];
关于ios - 更改 NSAttributedString 中子字符串的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17486647/