53 lines
2.0 KiB
Swift
53 lines
2.0 KiB
Swift
//
|
||
// TextHighlightHelper.swift
|
||
// Crush
|
||
//
|
||
// Created by Leon on 2025/1/15.
|
||
//
|
||
|
||
import UIKit
|
||
|
||
/// 此方法:高亮部分是背景色不同,不是文字颜色
|
||
class TextHighlightHelper {
|
||
|
||
/// 为文本中的搜索关键词添加高亮样式
|
||
/// - Parameters:
|
||
/// - text: 原始文本
|
||
/// - searchText: 搜索关键词
|
||
/// - highlightColor: 高亮颜色
|
||
/// - Returns: 带有高亮样式的NSAttributedString
|
||
static func highlightText(_ text: String, searchText: String, highlightColor: UIColor = UIColor.c.cpvn) -> NSAttributedString {
|
||
guard !searchText.isEmpty else {
|
||
return NSAttributedString(string: text)
|
||
}
|
||
|
||
let attributedString = NSMutableAttributedString(string: text)
|
||
let range = NSRange(location: 0, length: text.count)
|
||
|
||
// 使用正则表达式进行不区分大小写的搜索
|
||
do {
|
||
let regex = try NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: searchText), options: .caseInsensitive)
|
||
let matches = regex.matches(in: text, options: [], range: range)
|
||
|
||
// 为匹配的文本添加高亮样式
|
||
for match in matches {
|
||
// backgroundColor
|
||
attributedString.addAttribute(.foregroundColor, value: highlightColor, range: match.range)
|
||
}
|
||
} catch {
|
||
// 如果正则表达式失败,使用简单的字符串搜索
|
||
let lowercasedText = text.lowercased()
|
||
let lowercasedSearchText = searchText.lowercased()
|
||
|
||
var searchRange = lowercasedText.startIndex..<lowercasedText.endIndex
|
||
while let range = lowercasedText.range(of: lowercasedSearchText, range: searchRange) {
|
||
let nsRange = NSRange(range, in: text)
|
||
attributedString.addAttribute(.backgroundColor, value: highlightColor, range: nsRange)
|
||
searchRange = range.upperBound..<lowercasedText.endIndex
|
||
}
|
||
}
|
||
|
||
return attributedString
|
||
}
|
||
}
|