我有一个项目表,每个项目都有一个标签。我还有一个搜索栏,用于根据是否mySearchBar.text
为的子字符串来过滤表中的项目myLabel.text
。
一切正常,但我想将与搜索字符串匹配的标签文本部分加粗。
最终产品将类似于Google Maps搜索。
斯威夫特4:XCode 9.x
private 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 }
如何使用 :
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
}