概述
今天項(xiàng)目中遇到一個(gè)需求:UITextField中文本為空時(shí)亲桦,仍然能夠監(jiān)聽到鍵盤的刪除按鍵點(diǎn)擊事件
分析
當(dāng)UITextField中文本不為空時(shí)秉版,可以通過以下方式實(shí)現(xiàn)
textField.addTarget(self, action: #selector(textDidChanged(_:)), for: UIControlEvents.editingChanged)
但是蟋定,當(dāng)UITextField中文本為空時(shí)访忿,textDidChanged(_:)
不會(huì)被觸發(fā),因此需要其他的方式
查看UITextField API可以發(fā)現(xiàn)如下的系統(tǒng)事件
public protocol UIKeyInput : UITextInputTraits {
public var hasText: Bool { get }
public func insertText(_ text: String)
public func deleteBackward()
}
現(xiàn)在要做的就是實(shí)現(xiàn)該協(xié)議尝蠕,收到deleteBackward()
回調(diào)函數(shù)
然而該協(xié)議已經(jīng)被UITextField實(shí)現(xiàn)了联喘,只是沒有拋出來
@available(iOS 2.0, *)
open class UITextField : UIControl, UITextInput, NSCoding, UIContentSizeCategoryAdjusting
現(xiàn)在要做的就是從UITextField中拋出該函數(shù)
解決方案
自定義一個(gè)子類华蜒,繼承UITextField
import UIKit
protocol CustomTextFieldDelegate {
func textFieldBackKeyPressed(_ textField:UITextField)
}
class CustomTextField: UITextField {
var customTextFieldDelegate:CustomTextFieldDelegate?
override func deleteBackward() {
super.deleteBackward()
if customTextFieldDelegate != nil {
customTextFieldDelegate?.textFieldBackKeyPressed(self)
}
}
}
實(shí)際使用時(shí)
import UIKit
class ControlPadTextInput: UIView, CustomTextFieldDelegate{
private var inputRegion:CustomTextField!
override init(frame: CGRect) {
super.init(frame: frame)
inputRegion = CustomTextField.init(frame: CGRect(x: MARGIN_21_HOR, y: 0, width: DPAD_WIDTH - MARGIN_21_HOR*2, height: SIZE_32_HEIGHT))
inputRegion.customTextFieldDelegate = self
//... ...
}
func textFieldBackKeyPressed(_ textField: TextField) {
//do something
}
}