我想在iOS中突出顯示所選字符,就像您在iPhone iOS 7 Notes應用中看到的一樣。 當您搜索特定文本時,搜索字符將在UITableView
中顯示的結果中高亮顯示。在iOS中動態突出顯示所選字符
例子:
「這是我的名字」
^h - 應 '五個藍色
Ÿ - 應' 五個紅色
字符c ustomisation應該是動態的。我希望我已經足夠了。
尋找優秀的迴應夥伴!
我想在iOS中突出顯示所選字符,就像您在iPhone iOS 7 Notes應用中看到的一樣。 當您搜索特定文本時,搜索字符將在UITableView
中顯示的結果中高亮顯示。在iOS中動態突出顯示所選字符
例子:
「這是我的名字」
^h - 應 '五個藍色
Ÿ - 應' 五個紅色
字符c ustomisation應該是動態的。我希望我已經足夠了。
尋找優秀的迴應夥伴!
您可以輕鬆地設置一個歸因實現這字符串添加到顯示搜索結果條目的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;