我將在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