2014-03-26 85 views
1

我想在iOS中突出顯示所選字符,就像您在iPhone iOS 7 Notes應用中看到的一樣。 當您搜索特定文本時,搜索字符將在UITableView中顯示的結果中高亮顯示。在iOS中動態突出顯示所選字符

例子:

「這是我的名字」

^h - 應 '五個藍色

Ÿ - 應' 五個紅色

字符c ustomisation應該是動態的。我希望我已經足夠了。

尋找優秀的迴應夥伴!

回答

0

您可以輕鬆地設置一個歸因實現這字符串添加到顯示搜索結果條目的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:方法中創建單元格時,您只需設置UILabelattributedText

這應該指向你正確的方向。

1

嘗試在看看TextKit

This是一個不錯的網站,顯示你的基礎知識

我希望我理解你的問題..

0

使用NsMutableAttributedString突出人物

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:display]; 
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange([displayString length], ([details.notificationCount length]+2))]; 
displayLabel.attributedText  = str;