在searchDisplayController的结果中,如何突出显示UISearchBar中输入的字符串?

325*_*523 2 objective-c uitableview uisearchbar uisearchdisplaycontroller ios

我有一个searchDisplayController,我希望结果大胆出现在搜索栏中输入的任何字符串.

在此输入图像描述

在这种情况下,搜索结果的预期行为应该在搜索结果中突出显示字符串"Bla"(或更改为不同的样式 - 斜体等)

我试过调查NSMutableAttributedString和NSAttributedString,但是仍然有点不确定如何在搜索结果中更改字符串的样式

Jus*_*tyn 6

您可以使用以下方法执行您想要的操作.它基本上采用您的搜索字符串并创建一个正则表达式,用于在结果字符串中查找所有出现的搜索字符串.然后,我们遍历这些结果并将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;
Run Code Online (Sandbox Code Playgroud)

这会给你这样的东西: 在此输入图像描述