在TableView中突出显示搜索字母-iOS

时间:2019-02-06 11:50:04

标签: ios swift uitableview highlight uisearchbardelegate

我在UISearchBar中实现了UITableView。现在,我要突出显示搜索列表的结果。例如,如果我输入三个字母,则这些字母应在从搜索栏下拉的结果TableView中突出显示。

1 个答案:

答案 0 :(得分:0)

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

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

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

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

return attributedString

}

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