我有一个项目表,每个项目都有一个标签.我还有一个搜索栏,用于根据mySearchBar.text是myLabel.text的子字符串来过滤表中的项目. 这一切都运行正常,但我想加粗与搜索字符串匹配的标签文本部
这一切都运行正常,但我想加粗与搜索字符串匹配的标签文本部分.
最终产品类似于谷歌地图搜索.
Swift 4:XCode 9.xprivate func filterAndModifyTextAttributes(searchStringCharacters: String, completeStringWithAttributedText: String) -> NSMutableAttributedString { let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: completeStringWithAttributedText) let pattern = searchStringCharacters.lowercased() let range: NSRange = NSMakeRange(0, completeStringWithAttributedText.characters.count) var regex = NSRegularExpression() do { regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options()) regex.enumerateMatches(in: completeStringWithAttributedText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) in let subRange = textCheckingResult?.range let attributes : [NSAttributedStringKey : Any] = [.font : UIFont.boldSystemFont(ofSize: 17),.foregroundColor: UIColor.red ] attributedString.addAttributes(attributes, range: subRange!) } }catch{ print(error.localizedDescription) } return attributedString }
How to use :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle , reuseIdentifier: "Cell") cell.textLabel?.attributedText = self.filterAndModifyTextAttributes(searchStringCharacters: self.textFromSearchBar, completeStringWithAttributedText: searchResultString) return cell
}