这个问题可能是这个问题的重复。但答案对我不起作用,我想更具体一些。
我有 a NSString
,但我需要 aNS(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 保留属性映射。但是用我的替换物,我在分配的右侧没有更多的属性字符串(在我的代码片段的最后一行)。
我怎样才能得到我想要的?;)