2014-09-03 42 views
0

我想讓這些匹配在TextView中是藍色的。如何使突出顯示的匹配(NSRegularExpression)?

NSString *text = @"Except as contained in #wep this notice, the name of a copyright #ololo holder shall not be used in #pewpewpew advertising or otherwise to #promote"; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#\\w*" options:0 error:NULL]; 
NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])]; 
NSLog(@"count %d", matches.count); 

for (NSTextCheckingResult *match in matches) { 
    NSRange matchRange = [match range]; 
    NSString *match = [text substringWithRange:matchRange]; 
    NSLog(@"Matched string: %@", match); 
} 
self.myTextView.text = text; 
+1

使用'NSMutableAttributedString' – Hokage 2014-09-03 12:32:22

回答

1

你必須創建NSAttributedString,然後應用字體按範圍和設定attributedText您UITextView不是一個簡單的文本。

你的代碼應該如下所示。

NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithString:text]; 

for (NSTextCheckingResult *match in matches) { 
    NSRange matchRange = [match range]; 
    NSString *match = [text substringWithRange:matchRange]; 
    NSLog(@"Matched string: %@", match); 
    // set your rgb color here which you want i added blue color. 
    [attrib addAttribute:NSForegroundColorAttributeName 
        value:[UIColor blueColor] 
        range:matchRange]; 
} 
// set attributed text not a normal text. 
self.myTextView.attributedText = attrib; 

也許這會幫助你。

+0

OK。以及如何進行按鈕匹配? – SpaceInvader 2014-09-03 13:13:02

+0

意思不明白。 – 2014-09-03 13:16:17

+0

匹配作爲按鈕(UIButton) – SpaceInvader 2014-09-03 13:19:23

0
self.myTextView.attributedText = // your attributed string here