2012-03-16 75 views
1

我知道在CFAttributedString不响应像NSString的stringByReplacingOccurrencesOfString:withString:方法的任何方法,我找不到可以使用CF(可变)AttributedString做到这一点的方法。CFAttributedString替换字符串的出现?

我想用相同的文本替换字符串中的某些文本,但使用另一种颜色,例如,我有字符串@"This is a text",我想更改单词“text”的颜色。

我希望问题很清楚,如果不是,请问我。

谢谢。

+0

所以......你不想改变文本,只是一个子范围的属性(例如字体颜色),是正确的? – Alladinian 2012-03-16 14:55:57

+0

是的,我认为改变文字是最简单的方法,但我不知道,所以如果你有另一种解决方案... – Garoal 2012-03-16 16:15:54

回答

2

我将在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"]; 
+0

我会尝试它,如果它的工作,我会接受你的答案。但我想要一个类似但不相等的CFAttributedString,所以我会尝试将其改为 – Garoal 2012-03-16 16:18:08

+0

“CFMutableAttributedStringRef”和“NSMutableAttributedString”完全可以互换,如[免费桥接](http:// developer。 apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFDesignConcepts/Articles/tollFreeBridgedTypes.html)文档。 – 2012-03-16 16:26:09

+0

好吧抱歉,我经历了他们不完全一样 – Garoal 2012-03-16 16:32:45

0

重:免费电话桥接

CFAtttributeString和NSAttributeString有不同的属性键。

Ex。颜色Mac OS X:

NSForegroundColorAttributeName - NSColor - 默认blackColor kCTForegroundColorAttributeName - 与此属性关联的值必须是CGColor对象。默认值是黑色。