iOS富文本高亮

多个predicates

use NSCompoundPredicate for your multiple predicates, you can refer NSCompoundPredicate Class Reference

Use NSPredicate to search multiple fields

NSPredicate endswith multiple files

NSStringEnumerationOptions 说明
NSStringEnumerationByLines 按行
NSStringEnumerationByParagraphs 段落
NSStringEnumerationByComposedCharacterSequences 字符顺序
NSStringEnumerationByWords 单词,字
NSStringEnumerationBySentences 句子
NSStringEnumerationReverse 反向遍历
NSStringEnumerationSubstringNotRequired 不需要子字符串
NSStringEnumerationLocalized
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(void)processEditing
{
NSRange paragaphRange = [self.string paragraphRangeForRange:self.editedRange];
NSArray *extensions = [NSArray arrayWithObjects:@"strong", @"copy", @"assign", @"nonatomic", nil];
NSPredicate *predicateWords =[NSPredicate predicateWithFormat:@"SELF IN %@", extensions];
// 创建谓词对象并设定条件的表达式
// NSPredicate *predicateNS = [NSPredicate predicateWithFormat:@"SELF MATCHES '%@'",kATPattern];
NSPredicate *predicateWD = [NSCompoundPredicate orPredicateWithSubpredicates:@[predicateWords]];

[self.string enumerateSubstringsInRange:paragaphRange options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
NSLog(@"substring=%@",substring);
if ([predicateWD evaluateWithObject:substring]){
[self setAttributes:@{NSForegroundColorAttributeName:[NSColor redColor]} range:substringRange]; //当出现关键词如strong单词时字体变红
}
}];
}

多个匹配命令

1
2
3
4
5
6
7
// 按顺序获得所有(包括不匹配)字段的 range 数组以重新拼接
NSString *regex = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@",kUserPattern, kCopyPattern, kNonatomicPattern, kNSClassPattern,kStrongPattern,kAssignPattern];
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:nil];
[expression enumerateMatchesInString:self.string options:0 range:paragaphRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// Add red highlight color
[self addAttribute:NSForegroundColorAttributeName value:RGB(194, 53, 154) range:result.range];
}];

https://github.com/GGGHub/TextKitDemo/blob/master/TextKitDemo/TextKitDemo/LSYTextStorage.m

https://github.com/Desgard/Shanbei-Homework/blob/master/Shanbei%20Homework/HighlightingTextStorage.m

iOS富文本(三)深入使用Text Kit

Multiple NSPredicate

文章作者: kyren
文章链接: http://huluo666.github.io/2017/11/04/iOS:Mac文本高亮/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Kyren's Blog