【发布时间】:2014-03-26 17:15:56
【问题描述】:
我想在 iOS 中突出显示选定的字符,正如您在 iPhone iOS 7 Notes 应用中看到的那样。
当您搜索特定文本时,搜索字符将在UITableView 中显示的结果中突出显示。
例子:
“这是我的名字”
h - 应该是蓝色
y - 应该是红色
角色定制应该是动态的。我希望我已经介绍得够多了。
寻找优秀的响应伙伴!
【问题讨论】:
标签: ios objective-c cocoa-touch
我想在 iOS 中突出显示选定的字符,正如您在 iPhone iOS 7 Notes 应用中看到的那样。
当您搜索特定文本时,搜索字符将在UITableView 中显示的结果中突出显示。
例子:
“这是我的名字”
h - 应该是蓝色
y - 应该是红色
角色定制应该是动态的。我希望我已经介绍得够多了。
寻找优秀的响应伙伴!
【问题讨论】:
标签: ios objective-c cocoa-touch
【讨论】:
您可以通过在显示搜索结果条目的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 的attributedText。
这应该为您指明正确的方向。
【讨论】:
使用 NsMutableAttributedString 突出显示字符
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:display];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange([displayString length], ([details.notificationCount length]+2))];
displayLabel.attributedText = str;
【讨论】: