在UITableView单元格iOS Swift中突出显示搜索结果

问题描述 投票:4回答:5

我在TableView中实现了一个搜索栏。现在我想强调一下结果。例如,如果我输入了两个字母,那么这两个字母应该在从搜索栏下拉的结果TableView中突出显示。任何人都可以帮我这样做吗?我知道我应该使用自定义单元格,但我没有实现它。

ios uitableview highlight searchbar
5个回答
12
投票

这是在tableview中对文本进行属性的第二种方法

   let initialtext =   "Hello World"
    let attrString: NSMutableAttributedString = NSMutableAttributedString(string: initialtext)

let range: NSRange = (initialtext as NSString).rangeOfString(("World" , options:NSStringCompareOptions.CaseInsensitiveSearch])


    attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)


    cell!.textLabel?.attributedText = attrString

10
投票

@Vijay对这篇文章有一个很好的正确答案。

我通过创建一个函数接受searchString和你想要修改的字符串 - resultString - 并返回一个可以应用于attributedStringUILabel来为我自己的目的(在我的搜索结果中加粗文本)修改了这个。

我也对lowercaseString属性进行了检查,因此无论我在搜索栏中输入什么内容,我的字符串都会匹配字符而不是大小写(此要求可能会有所不同,具体取决于您的用例)。

func boldSearchResult(searchString: String, resultString: String) -> NSMutableAttributedString {

    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: resultString)
    let pattern = searchString.lowercaseString
    let range: NSRange = NSMakeRange(0, resultString.characters.count)

    let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())

    regex.enumerateMatchesInString(resultString.lowercaseString, options: NSMatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
        let subRange = textCheckingResult?.range
        attributedString.addAttribute(NSFontAttributeName, value: UIFont.customBoldedFontNameWithSize(15.0), range: subRange!)
    }

    return attributedString

}

注意:我有一个自定义粗体字体可以使用,但你总是可以使用UIFont.boldSystemFontOfSize(fontSize: CGFloat)或类似的东西来获得类似的效果。

然后,只需通过执行(某些变体)将结果添加到您的标签:

cell.myCustomLabel.attributedText = boldSearchResult(mySearchText, resultString: textForBolding)

4
投票

您可以通过从结果字符串中查找搜索字符串范围并在该范围添加属性字符串来实现此目的。找到下面的示例代码,

Objective-C的

NSString *searchTerm = /* SEARCH_TERM */;
NSString *resultText = /* YOUR_RESULT_TEXT */;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:resultText];

NSString *pattern = [NSString stringWithFormat:@"(%@)", searchTerm];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:nil];
NSRange range = NSMakeRange(0, resultText.length);

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

    NSRange subStringRange = [result rangeAtIndex:1];

    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:subStringRange];
}];

斯威夫特(测试)

let searchTerm = "" /* SEARCH_TERM */
let resultText = "" /* YOUR_RESULT_TEXT */
let attributedString:NSMutableAttributedString = NSMutableAttributedString(string: resultText)
let pattern = "(\(searchTerm))"
let range:NSRange = NSMakeRange(0, resultText.characters.count)

let regex = try! NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions())
regex.enumerateMatchesInString(
     resultText,
     options: NSMatchingOptions(),
     range: range,
     usingBlock: {
        (textCheckingResult, matchingFlags, stop) -> Void in
           let subRange = textCheckingResult?.range
            attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: subRange!)
            }
        )

0
投票

试图尽可能保持苗条。该函数返回一个以粗体显示searchText的属性字符串。 Swift 4.2+

  private func boldedString(with baseString: String, searchString: String, fontSize: CGFloat) -> NSAttributedString? {
    guard let regex = try? NSRegularExpression(pattern: searchString, options: .caseInsensitive) else {
        return nil
    }

    let attributedString = NSMutableAttributedString(string: baseString)
    let boldFont = UIFont.systemFont(ofSize: fontSize, weight: .bold)
    regex
      .matches(in: baseString, options: .withTransparentBounds,
               range: NSRange(location: 0, length: baseString.utf16.count))
      .forEach {
        attributedString.addAttributes([.font: boldFont], range: $0.range)
    }
    return attributedString
  }

在单元格中,您需要添加这样的代码进行配置:

func configure(with text: String, searchText: String?) {
  if let boldedAddress = boldedString(with: text,
                                      searchString: searchText,
                                      fontSize: titleLabel.font.pointSize) {
    titleLabel.attributedText = boldedAddress
  } else {
    titleLabel.text = locationInfo.location.address
  }
}

0
投票

Swift 5版Vijayvir的回答:

let initialtext = "Hello, World!"

let attrString: NSMutableAttributedString = NSMutableAttributedString(string: initialtext)

let range = (initialtext as NSString).range(of: "World", options: .caseInsensitive)

attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

cell.textLabel?.attributedText = attrString
© www.soinside.com 2019 - 2024. All rights reserved.