在iOS中动态高亮显示选定字符
我想在iOS中突出显示选中的字符,正如你在iPhone iOS 7 Notes应用程序中看到的那样。 搜索特定文本时,搜索字符将在在iOS中动态高亮显示选定字符,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,我想在iOS中突出显示选中的字符,正如你在iPhone iOS 7 Notes应用程序中看到的那样。 搜索特定文本时,搜索字符将在UITableView中显示的结果中突出显示 例如: “这是我的名字” h-应为蓝色 y-应该是红色 角色定制应该是动态的。我希望我已经介绍得够多了 寻找优秀的反应朋友 试试看TextKit 是一个很好的网站,向你展示了基本知识 我希望我理解了您的问题。您可以通过在显示搜索结果条目的UITableViewCell中的文本标签上设置属性字符串来轻松实现这一点 您需要计算
UITableView
中显示的结果中突出显示
例如:
“这是我的名字”
h-应为蓝色
y-应该是红色
角色定制应该是动态的。我希望我已经介绍得够多了
寻找优秀的反应朋友 试试看TextKit 是一个很好的网站,向你展示了基本知识
我希望我理解了您的问题。您可以通过在显示搜索结果条目的
UITableViewCell
中的文本标签上设置属性字符串来轻松实现这一点
您需要计算应该高亮显示的子字符串的范围。正如我在示例代码中所写的那样,可以使用正则表达式来实现。通过这种方式,您可以支持子字符串在字符串中多次出现
然后,当您具有范围时,只需应用特殊属性并设置单元格标签的attributedText
属性
代码可能如下所示:
NSString *searchTerm = ...;
NSString *text = @"This is a sample text that is super cool";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSString *pattern = [NSString stringWithFormat:@"(%@)", searchTerm];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:kNilOptions
error:nil];
NSRange range = NSMakeRange(0, text.length);
[regex enumerateMatchesInString:text
options:kNilOptions
range:range
usingBlock:^(NSTextCheckingResult *result,
NSMatchingFlags flags,
BOOL *stop)
{
NSRange subStringRange = [result rangeAtIndex:1];
[attributedString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor]
range:subStringRange];
}];
那就容易了。在tableView:cellForRowAtIndexPath:
方法中创建单元格时,只需设置UILabel
的attributeText
这将为您指明正确的方向。使用NsMutableAttributedString突出显示字符
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:display];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange([displayString length], ([details.notificationCount length]+2))];
displayLabel.attributedText = str;