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

 xkxk22 发布于 2023-02-09 12:41

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

在此输入图像描述

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

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

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

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

    2023-02-09 12:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有