我试图检查当一个文本字段发生变化时,等效于textView - textViewDidChange的函数,到目前为止我已经做到了这一点:
func textFieldDidBeginEditing(textField: UITextField) {
if self.status.text == "" && self.username.text == "" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
}
哪种类型的工作,但topRightButton一经文本字段被按下就被启用,我想它只在文本实际输入时才被启用?
textField(_:shouldChangeCharactersIn:replacementString:)在Xcode 8中为我工作,Swift 3如果你想检查每一个按键。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Whatever code you want to run here.
// Keep in mind that the textfield hasn't yet been updated,
// so use 'string' instead of 'textField.text' if you want to
// access the string the textfield will have after a user presses a key
var statusText = self.status.text
var usernameText = self.username.text
switch textField{
case self.status:
statusText = string
case self.username:
usernameText = string
default:
break
}
if statusText == "" && usernameText == "" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
//Return false if you don't want the textfield to be updated
return true
}
斯威夫特5.0
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: .editingChanged)
及处理方法:
@objc func textFieldDidChange(_ textField: UITextField) {
}
斯威夫特4.0
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
及处理方法:
@objc func textFieldDidChange(_ textField: UITextField) {
}
斯威夫特3.0
textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
及处理方法:
func textFieldDidChange(textField: UITextField) {
}