gpt4 book ai didi

ios - 如何进行高亮匹配(NSRegularExpression)?

转载 作者:行者123 更新时间:2023-11-29 02:42:00 34 4
gpt4 key购买 nike

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

最佳答案

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

也许这对你有帮助。

关于ios - 如何进行高亮匹配(NSRegularExpression)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25644382/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com