66 lines
2.3 KiB
Swift
66 lines
2.3 KiB
Swift
//
|
|
// gp_textV.swift
|
|
// Hthik
|
|
//
|
|
// Created by 忆海16 on 2024/5/31.
|
|
// Copyright © 2024 Hthik. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
import UIKit
|
|
|
|
class TextViewModifier {
|
|
|
|
// 修改TextView的文本
|
|
static func setText(of textView: UITextView, to text: String) {
|
|
textView.text = text
|
|
}
|
|
|
|
// 修改TextView的文本颜色
|
|
static func setTextColor(of textView: UITextView, to color: UIColor) {
|
|
textView.textColor = color
|
|
}
|
|
|
|
// 修改TextView的背景颜色
|
|
static func setBackgroundColor(of textView: UITextView, to color: UIColor) {
|
|
textView.backgroundColor = color
|
|
}
|
|
|
|
// 修改TextView的字体
|
|
static func setFont(of textView: UITextView, to font: UIFont) {
|
|
textView.font = font
|
|
}
|
|
|
|
// 设置TextView的占位符
|
|
static func setPlaceholder(of textView: UITextView, to placeholder: String, placeholderColor: UIColor = .lightGray) {
|
|
textView.text = placeholder
|
|
textView.textColor = placeholderColor
|
|
textView.delegate = TextViewPlaceholderDelegate.shared
|
|
TextViewPlaceholderDelegate.shared.setPlaceholder(textView: textView, placeholder: placeholder, placeholderColor: placeholderColor)
|
|
}
|
|
}
|
|
|
|
// 用于处理占位符逻辑的委托类
|
|
class TextViewPlaceholderDelegate: NSObject, UITextViewDelegate {
|
|
static let shared = TextViewPlaceholderDelegate()
|
|
private var placeholderMap = [UITextView: (placeholder: String, placeholderColor: UIColor, originalColor: UIColor)]()
|
|
|
|
func setPlaceholder(textView: UITextView, placeholder: String, placeholderColor: UIColor) {
|
|
let originalColor = textView.textColor ?? .black
|
|
placeholderMap[textView] = (placeholder, placeholderColor, originalColor)
|
|
}
|
|
|
|
func textViewDidBeginEditing(_ textView: UITextView) {
|
|
guard let placeholderData = placeholderMap[textView], textView.text == placeholderData.placeholder else { return }
|
|
textView.text = nil
|
|
textView.textColor = placeholderData.originalColor
|
|
}
|
|
|
|
func textViewDidEndEditing(_ textView: UITextView) {
|
|
guard let placeholderData = placeholderMap[textView], textView.text.isEmpty else { return }
|
|
textView.text = placeholderData.placeholder
|
|
textView.textColor = placeholderData.placeholderColor
|
|
}
|
|
}
|