ios - 将与搜索字符串匹配的字符串的一部分加粗

标签 ios swift string search bold

我有一个项目表,每个项目都有一个标签。我还有一个搜索栏,用于根据 mySearchBar.text 是否是 myLabel.text 的子字符串来过滤表中的项目。

一切正常,但我想将与搜索字符串匹配的标签文本部分加粗。

最终产品将类似于 Google map 搜索。

enter image description here

最佳答案

swift 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
}

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

}

RESULT

关于ios - 将与搜索字符串匹配的字符串的一部分加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625631/

相关文章:

ios - GPUImage2 , 前后摄像头切换

ios - UIkit Dynamics in swift

java - 如何在 Java 中格式化多个字符串参数

java - 如何使用bufferedreader在java中接受字符串数组

ios - 尝试每 2 个 indexPath.row swift 添加一个部分

ios - 在 Swift 中获取和设置不同的数据类型

ios - 类型 'ChatViewController' 没有成员 'showOrHideKeyboard'

swift - "Unwind"从任何 View Controller 返回 Storyboard的初始 View Controller

ios - Xcode 9 更新 Swift,紫色警告

java - 字符串采访