更改NSAttributedString中子字符串的属性

mja*_*jay 17 replace objective-c nsattributedstring ios

这个问题可能是重复的这一个.但答案对我不起作用,我希望更具体.

我有一个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]];
Run Code Online (Sandbox Code Playgroud)

"和"应该是大写的红色.

文档说mutableString保留属性映射.但是对于我的替换事物,我在赋值的右侧(在我的代码片段的最后一行)中没有更多的claimString.

我怎样才能得到我想要的东西?;)

Mic*_*lum 35

@Hyperlord的答案将起作用,但前提是输入字符串中出现单词"and".无论如何,我要做的是使用NSString stringByReplacingOccurrencesOfString:最初将每个"和"更改为"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];
}];
Run Code Online (Sandbox Code Playgroud)

最后,只需将属性字符串应用于您的标签即可.

[myLabel setAttributedText:mutableAttributedString];
Run Code Online (Sandbox Code Playgroud)


小智 18

我认为你应该创建一个NSMutableAttributedString使用现有的NSString,然后添加适当的样式属性,NSRange以便着色你想要强调的部分,例如:

NSString *text = @"This is the text and i want to replace something";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:text];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:[text rangeOfString:@"and"]];
Run Code Online (Sandbox Code Playgroud)

请注意:这只是我的头脑而没有经过测试;-)