我创建了一个自定义文本字段,一个扩展UITextField的类,我怎么知道UITextField是否有值,我已经尝试了shouldChangeCharactersIn
,但什么都没发生。
这是我的自定义UITextField类的代码
@IBDesignable class CustomTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
loadContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadContent()
}
...
}
如果UITextField为空或用户删除了其中的值,则我想打印"the textfield is blank"
;如果其中有值或用户添加了值,则打印"the textfield has content"
。
您只需要在UIControl.Event
.editingChanged
的文本字段中添加一个目标
override func willMove(toSuperview newSuperview: UIView?) {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
使用UIKeyInput
方法hasText
检查您的字段是否为空:
@objc func editingChanged(_ textField: UITextField) {
print("the textfield " + (hasText ? "has content" : "is blank"))
}