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