Color all occurrences of string in swift

前端 未结 6 1062
旧巷少年郎
旧巷少年郎 2020-11-29 11:33

This code

var textSearch=\"hi\"
var textToShow=\"hi hihi hi\" 
var rangeToColor = (textToShow as NSString).rangeOfString(textSearch)
var attributedString =          


        
6条回答
  •  醉酒成梦
    2020-11-29 11:33

    I made those two methods to either color for only once occurrence or color all the occurrence for that text:

    extension NSMutableAttributedString{
        func setColorForText(_ textToFind: String, with color: UIColor) {
            let range = self.mutableString.range(of: textToFind, options: .caseInsensitive)
            if range.location != NSNotFound {
                addAttribute(NSForegroundColorAttributeName, value: color, range: range)
            }
        }
    
        func setColorForAllOccuranceOfText(_ textToFind: String, with color: UIColor) {
            let inputLength = self.string.count
            let searchLength = textToFind.count
            var range = NSRange(location: 0, length: self.length)
    
            while (range.location != NSNotFound) {
                range = (self.string as NSString).range(of: textToFind, options: [], range: range)
                if (range.location != NSNotFound) {
                    self.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: range.location, length: searchLength))
                    range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
                }
            }
        }
    }
    

提交回复
热议问题