UITextView highlight all matches using swift

前端 未结 7 1482
南方客
南方客 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:45

    Improved customized solution for Swift 4.2

    extension NSAttributedString {
        convenience init(base: String,
                         keyWords: [String],
                         foregroundColor: UIColor,
                         font: UIFont,
                         highlightForeground: UIColor,
                         highlighBackground: UIColor) {
            let baseAttributed = NSMutableAttributedString(string: base, attributes: [NSAttributedString.Key.font: font,
                                                                                      NSAttributedString.Key.foregroundColor: foregroundColor])
            let range = NSRange(location: 0, length: base.utf16.count)
            for word in keyWords {
                guard let regex = try? NSRegularExpression(pattern: word, options: .caseInsensitive) else {
                    continue
                }
    
                regex
                    .matches(in: base, options: .withTransparentBounds, range: range)
                    .forEach { baseAttributed
                        .addAttributes([NSAttributedString.Key.backgroundColor: highlighBackground,
                                        NSAttributedString.Key.foregroundColor: highlightForeground],
                                       range: $0.range) }
            }
            self.init(attributedString: baseAttributed)
        }
    }
    

提交回复
热议问题