[英]Highlighted lower & upper case text using by NSMutableAttributedString
I having text is " God is great, and the great god absolute!, GOD bless me." 我的文字是“ 上帝是伟大的,伟大的上帝是绝对的! 上帝保佑我。” I have displayed this text in
tableviewcell
and I used NSMutableAttributedString
. 我已经在
tableviewcell
显示了此文本,并且使用了NSMutableAttributedString
。
Example 1. GOD 2. God 3. god 示例1.神2.神3.神
When I search text "god" it highlights text like "god" but I need highlight a text like GOD, God and god whatever it should be highlighted. 当我搜索文本“上帝”时,它会突出显示诸如“上帝”之类的文本,但是我需要突出显示诸如上帝,上帝和上帝之类的文本,无论该文本应如何突出显示。
code 码
NSString *initial = [NSString stringWithFormat:@"%@ %d - %d : %@",[appDelegate.arrChapterName objectAtIndex:nBookNo-1],[[arrVerses objectAtIndex:1] integerValue],[[arrVerses objectAtIndex:2] integerValue],[arrVerses objectAtIndex:3]];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:initial];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)",searchBar.text] options:kNilOptions error:nil];
NSRange range = NSMakeRange(0,initial.length);
[regex enumerateMatchesInString:initial options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:1];
[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor lightGrayColor] range:subStringRange];
}];
cell.textLabel.attributedText = mutableAttributedString;
Consider replacing your regex expression with the following code: 考虑用以下代码替换您的正则表达式:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)",searchBar.text]
options:NSRegularExpressionCaseInsensitive error:nil];
For more information and example refer here . 有关更多信息和示例,请参见此处 。
Here you go, 干得好,
NSString *initial = [NSString stringWithFormat:@"%@ %d - %d : %@",[appDelegate.arrChapterName objectAtIndex:nBookNo-1],[[arrVerses objectAtIndex:1] integerValue],[[arrVerses objectAtIndex:2] integerValue],[arrVerses objectAtIndex:3]];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:initial];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)",searchBar.text] options:NSRegularExpressionCaseInsensitive error:nil];
NSRange range = NSMakeRange(0,initial.length);
[regex enumerateMatchesInString:initial options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:1];
[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIFont boldSystemFontOfSize:12.0] range:subStringRange];
}];
cell.textLabel.attributedText = mutableAttributedString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.