LNTextField.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // LNTextField.swift
  3. // Gami
  4. //
  5. // Created by OneeChan on 2026/1/29.
  6. //
  7. import Foundation
  8. import UIKit
  9. protocol LNTextFieldDelegate: NSObject {
  10. func onDeleteBackward(_ textField: UITextField, oldText: String?)
  11. }
  12. class LNTextField: UITextField {
  13. weak var exDelegate: LNTextFieldDelegate?
  14. // 自定义光标高度(可根据需求修改,如25、30)
  15. var cursorHeight: CGFloat = 20
  16. // 自定义光标宽度(默认系统宽度约1pt,可微调)
  17. var cursorWidth: CGFloat = 1.0
  18. override func caretRect(for position: UITextPosition) -> CGRect {
  19. // 1. 获取系统默认的光标矩形(保留水平位置、基础属性)
  20. var originalRect = super.caretRect(for: position)
  21. // 2. 计算光标垂直居中的y值:(文本框高度 - 自定义光标高度) / 2
  22. let centerY = (self.bounds.height - cursorHeight) / 2
  23. // 3. 重新设置光标矩形:指定宽度、自定义高度、垂直居中
  24. originalRect.size.width = cursorWidth
  25. originalRect.size.height = cursorHeight
  26. originalRect.origin.y = centerY
  27. return originalRect
  28. }
  29. override func deleteBackward() {
  30. let oldText = text
  31. super.deleteBackward()
  32. exDelegate?.onDeleteBackward(self, oldText: oldText)
  33. }
  34. }