搜索输入搜索内容时需要进行关键词的联想,匹配的关键词进行高亮显示,这里使用忽略大小写的匹配规则,如果需要精准匹配,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<Index>] = []
while let range = range(of: substring, options: options, range: (ranges.last?.upperBound ?? self.startIndex)..<self.endIndex, locale: locale) {
ranges.append(range)
}
// [range]转换为[NSRange]返回
return ranges.compactMap({NSRange($0, in: self)})
}
/// range转换为NSRange
func toNSRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
}
网友评论