我想在TextView中使匹配为蓝色。
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;
答案 0 :(得分: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;
也许这会对你有帮助。
答案 1 :(得分:0)
self.myTextView.attributedText = // your attributed string here