Visual_Novel_iOS/crush/Crush/Src/Utils/TextHighlightHelper.swift

53 lines
2.0 KiB
Swift
Raw Normal View History

2025-10-09 10:29:35 +00:00
//
// 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
}
}