// // SPTextField.swift // Thimra // // Created by 曾觉新 on 2025/4/17. // import UIKit class SPTextField: UITextField { ///0 不限制字数 var maxNumber = 0 var currentNumber = 0 ///是否为手机格式 var isPhone: Bool = false var textDidChange: ((_ text: String) -> Void)? var sp_placeholder: String? { set { _createAttributedPlaceholder() let newStr = NSMutableAttributedString(string: newValue ?? "") newStr.font = self.sp_placeholderFont newStr.color = self.sp_placeholderColor _attributedPlaceholder = newStr self.attributedPlaceholder = _attributedPlaceholder } get { return _attributedPlaceholder?.string } } var sp_placeholderFont: UIFont? { set { _createAttributedPlaceholder() _attributedPlaceholder?.font = newValue self.attributedPlaceholder = _attributedPlaceholder } get { if let font = _attributedPlaceholder?.font { return font } else { return self.font } } } var sp_placeholderColor: UIColor? { set { _createAttributedPlaceholder() _attributedPlaceholder?.color = newValue self.attributedPlaceholder = _attributedPlaceholder } get { if let color = _attributedPlaceholder?.color { return color } else { return .placeholderColor() } } } private var _attributedPlaceholder: NSMutableAttributedString? private func _createAttributedPlaceholder() { if self._attributedPlaceholder == nil { _attributedPlaceholder = NSMutableAttributedString(string: "") _attributedPlaceholder?.font = self.font _attributedPlaceholder?.color = .placeholderColor() self.attributedPlaceholder = _attributedPlaceholder } } deinit { NotificationCenter.default.removeObserver(self) } override init(frame: CGRect) { super.init(frame: frame) NotificationCenter.default.addObserver(self, selector: #selector(textDidChangeNotification(sender:)), name: UITextField.textDidChangeNotification, object: nil) // var iq = self.iq // iq.enableMode = .enabled self.textColor = .colorFFFFFF() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SPTextField { @objc func textDidChangeNotification(sender: Notification){ guard let object = sender.object else { return } if !(object is UITextField) {return} if (object as! UITextField) != self {return} let selectedRange: UITextRange? = self.markedTextRange if selectedRange == nil { if !self.isPhone { if maxNumber > 0 { if self.text?.count ?? 0 > self.maxNumber { var string = self.text string?.removeLast(self.text!.count - self.maxNumber) self.text = string } } if let textDidChange = textDidChange { textDidChange(self.text ?? "") } } else { // var newString = self.text?.replacingOccurrences(of: " ", with: "") ?? "" // // if newString.count > self.maxNumber { // newString.removeLast(newString.count - self.maxNumber) // } // // self.text = newString.formatToPhone() // if let textDidChange = textDidChange { // textDidChange(newString) // } } self.currentNumber = self.text?.count ?? 0 } } }