【问题标题】:How to make the highlighted matches (NSRegularExpression)?如何进行突出显示的匹配(NSRegularExpression)?
【发布时间】:2014-09-07 20:24:48
【问题描述】:

我想让 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;

【问题讨论】:

  • 使用NSMutableAttributedString

标签: ios regex nsregularexpression


【解决方案1】:

您必须创建NSAttributedString,然后根据范围应用字体并将属性文本设置为您的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;

也许这会对你有所帮助。

【讨论】:

  • 好的。以及如何匹配一个按钮?
  • 意思是看不懂。
  • 作为按钮的匹配项(UIButton)
【解决方案2】:
self.myTextView.attributedText = // your attributed string here

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 2015-07-28
    • 2010-09-18
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 2014-05-25
    • 2017-09-28
    • 2012-12-09
    相关资源
    最近更新 更多