我试图检查当一个文本字段发生变化时,等效于textView - textViewDidChange的函数,到目前为止我已经做到了这一点:
func textFieldDidBeginEditing(textField: UITextField) {
if self.status.text == "" && self.username.text == "" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
}
哪种类型的工作,但topRightButton一经文本字段被按下就被启用,我想它只在文本实际输入时才被启用?
这是如何使用Swift 3添加textField文本更改监听器:
将你的类声明为UITextFieldDelegate
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
textField.addTarget(self, action: #selector(UITextFieldDelegate.textFieldShouldEndEditing(_:)), for: UIControlEvents.editingChanged)
}
然后只是传统地添加一个textFieldShouldEndEditing函数:
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // do stuff
return true
}
斯威夫特4
textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)
@objc func textIsChanging(_ textField:UITextField) {
print ("TextField is changing")
}
如果你想在用户完全输入后进行更改(一旦用户退出键盘或按enter键,它将被调用)。
textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)
@objc func textDidChange(_ textField:UITextField) {
print ("TextField did changed")
}
也许使用RxSwift ?
need
pod 'RxSwift', '~> 3.0'
pod 'RxCocoa', '~> 3.0'
明显地添加导入
import RxSwift
import RxCocoa
你有一个textfield: UITextField
let observable: Observable<String?> = textField.rx.text.asObservable()
observable.subscribe(
onNext: {(string: String?) in
print(string!)
})
你有其他3种方法。
onError
oncomplete
onDisposed
onNext
斯威夫特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) {
}