Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何进行突出显示的匹配(NSRegularExpression)?_Ios_Regex_Nsregularexpression - Fatal编程技术网

Ios 如何进行突出显示的匹配(NSRegularExpression)?

Ios 如何进行突出显示的匹配(NSRegularExpression)?,ios,regex,nsregularexpression,Ios,Regex,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 regularExpress

我想让文本视图中的匹配为蓝色

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;

您必须创建
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;

也许这会对您有所帮助。

使用
nsmutableAttributeString
OK。以及如何匹配按钮?表示无法理解。作为按钮的匹配(UIButton)
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;