簡體   English   中英

在searchDisplayController的結果中,如何突出顯示在UISearchBar中鍵入的字符串?

[英]in a searchDisplayController 's results, how can I highlight the string typed in in the UISearchBar?

我有一個searchDisplayController,我希望結果加粗顯示在搜索欄中鍵入的所有字符串。

在此處輸入圖片說明

在這種情況下,搜索結果的預期行為應在搜索結果中突出顯示字符串“ Bla”(或更改為其他樣式-斜體等)

我曾嘗試研究NSMutableAttributedString和NSAttributedString,但仍然不確定如何更改搜索結果中字符串的樣式

您可以使用以下內容執行所需的操作。 它基本上使用您的搜索字符串並創建一個正則表達式,該表達式將用於查找結果字符串中所有出現的搜索字符串。 然后,我們遍歷這些結果,並將font屬性更改為粗體。

NSString *searchText = @"searc";

NSString *resultsText = @"I want to highlight what I'm searching for in these search results. Searching can often…";

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:resultsText];

NSString * regexPattern = [NSString stringWithFormat:@"(%@)", searchText];

// We create a case insensitive regex passing in our pattern
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:nil];

NSRange range = NSMakeRange(0,resultsText.length);

[regex enumerateMatchesInString:resultsText
                        options:kNilOptions
                          range:range
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];

    // Make the range bold
    [mutableAttributedString addAttribute:NSFontAttributeName
                                    value:[UIFont fontWithName:@"Helvetica-Bold" size:15.0]
                                    range:subStringRange];
}];

// Replace your result string with the updated attributed string
self.resultLabel.attributedText = mutableAttributedString;

這會給你這樣的東西: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM