Color all occurrences of string in swift

前端 未结 6 1061
旧巷少年郎
旧巷少年郎 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:47

    Using NSRegularExpression saves you from doing all the range calculations on by yourself. This example also will highlight two words instead of just one.

    let text = "If you don't have a plan, you become part of somebody else's plan."
    let toHighlight = ["plan", "you"]
    let range = text.nsRange(from: text.startIndex ..< text.endIndex) // full text
    
    let rangesToHighlight: [[NSRange]] = toHighlight.map { search in
        do {
            let regex = try NSRegularExpression(pattern: search, options: [])
            let matches: [NSTextCheckingResult] = regex.matches(in: text, options: [], range: range)
            return matches.map { $0.range } // get range from NSTextCheckingResult
        } catch {
            return [NSRange]()
        }
    }
    
    let yellow = UIColor.yellow
    let attributedText = NSMutableAttributedString(string: text)
    
    let flattenedRanges: [NSRange] = rangesToHighlight.joined()
    flattenedRanges.forEach { // apply color to all ranges
        attributedText.addAttribute(NSForegroundColorAttributeName,
                                    value: yellow,
                                    range: $0)
    }
    

提交回复
热议问题