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

53 lines
2.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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
}
}