这个问题可能是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]];

“和”应大写为红色。

该文档说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];

07-26 09:38
查看更多