Swift 指定关键词高亮、查找字符串中子字符串所有NSRange

搜索输入搜索内容时需要进行关键词的联想,匹配的关键词进行高亮显示,这里使用忽略大小写的匹配规则,如果需要精准匹配,options可以不传。

extension String {
    /// 指定关键词高亮
    /// - Parameter keyWords: 关键词
    /// - Parameter color: 高亮颜色
    func highlight(keyWords: String?, highlightColor color: UIColor) -> NSAttributedString {
        let string: String = self
        let attributeString = NSMutableAttributedString(string: string)
        guard let keyWords = keyWords else { return attributeString }
        let attribute: [NSAttributedString.Key: Any] = [.foregroundColor: color]
        // 需要改变的文本
        let ranges = ranges(of: keyWords, options: .caseInsensitive)
        for range in ranges where range.location + range.length <= string.count {
            attributeString.addAttributes(attribute, range: range)
        }
        return attributeString
    }
    
    /// 查找字符串中子字符串的NSRange
    /// - Parameters:
    ///   - substring: 子字符串
    ///   - options: 匹配选项
    ///   - locale: 本地化
    /// - Returns: 子字符串的NSRange数组
    func ranges(of substring: String, options: CompareOptions = [], locale: Locale? = nil) -> [NSRange] {
        var ranges: [Range] = []
        while let range = range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..) -> NSRange {
        return NSRange(range, in: self)
    }
}

你可能感兴趣的:(Swift 指定关键词高亮、查找字符串中子字符串所有NSRange)