2012-03-16 57 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對象。默認值是黑色。

相關問題