我将在NSMutableAttributedString
添加类别:
@implementation NSMutableAttributedString (MySearchAndReplaceCategory)
- (void)setAttributes:(NSDictionary *)attributes forOccurencesOfString:(NSString *)target
{
NSRange searchRange = NSMakeRange(0, self.length);
while (searchRange.length)
{
NSRange range = [self.string rangeOfString:target options:0 range:searchRange];
if (! range.length)
break;
[self setAttributes:attributes range:range];
searchRange.length = NSMaxRange(searchRange) - NSMaxRange(range);
searchRange.location = NSMaxRange(range);
}
}
@end
然后使用类似的东西:
UIColor *color = [UIColor greenColor];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:(__bridge id) color.CGColor
forKey:(__bridge id) kCTForegroundColorAttributeName];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"This is a text"];
[text setAttributes:attributes forOccurencesOfString:@"text"];
所以......你不想改变文本,只是一个子范围的属性(例如字体颜色),是正确的? – Alladinian 2012-03-16 14:55:57
是的,我认为改变文字是最简单的方法,但我不知道,所以如果你有另一种解决方案... – Garoal 2012-03-16 16:15:54