UITextView highlight all matches using swift

前端 未结 7 1466
南方客
南方客 2020-12-08 09:26

I want to highlight all matches word with searching. I wrote code but I couldn\'t use a loop. When i search a word, my app find words and highlight only first word. here is

7条回答
  •  一整个雨季
    2020-12-08 09:33

    I want to little improve the solution provided by @Barath and @Bruno Paulino, as this solution won't work with escaped characters like {}[]()'", this solution works with escaped characters, this solution written in SWIFT 5.

    func generateAttributedString(with searchTerm: String, targetString: NSAttributedString) -> NSAttributedString? {
        let attributedString = NSMutableAttributedString(attributedString: targetString)
        do {
    
            let regex = try NSRegularExpression(pattern:  NSRegularExpression.escapedPattern(for: searchTerm).trimmingCharacters(in: .whitespacesAndNewlines).folding(options: .regularExpression, locale: .current), options: .caseInsensitive)
            let range = NSRange(location: 0, length: targetString.string.utf16.count)
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.clear, range: range)
            for match in regex.matches(in: targetString.string.folding(options: .regularExpression, locale: .current), options: .withTransparentBounds, range: range) {
                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
            }
            return attributedString
        } catch {
            NSLog("Error creating regular expresion: \(error)")
            return nil
        }
    }
    

提交回复
热议问题