我试图检查当一个文本字段发生变化时,等效于textView - textViewDidChange的函数,到目前为止我已经做到了这一点:
func textFieldDidBeginEditing(textField: UITextField) {
if self.status.text == "" && self.username.text == "" {
self.topRightButton.enabled = false
} else {
self.topRightButton.enabled = true
}
}
哪种类型的工作,但topRightButton一经文本字段被按下就被启用,我想它只在文本实际输入时才被启用?
如果不可能将addTarget绑定到你的UITextField,我建议你像上面建议的那样绑定其中一个,并在shouldChangeCharactersIn方法的末尾插入执行代码。
nameTextField.addTarget(self, action: #selector(RegistrationViewController.textFieldDidChange(_:)), for: .editingChanged)
@objc func textFieldDidChange(_ textField: UITextField) {
if phoneNumberTextField.text!.count == 17 && nameTextField.text!.count > 0 {
continueButtonOutlet.backgroundColor = UIColor(.green)
} else {
continueButtonOutlet.backgroundColor = .systemGray
}
}
在调用中shouldChangeCharactersIn func。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let lastText = (text as NSString).replacingCharacters(in: range, with: string) as String
if phoneNumberTextField == textField {
textField.text = lastText.format("+7(NNN)-NNN-NN-NN", oldString: text)
textFieldDidChange(phoneNumberTextField)
return false
}
return true
}
斯威夫特
斯威夫特4.2
textfield.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
and
@objc func textFieldDidChange(_ textField: UITextField) {
}
SWIFT 3和SWIFT 4.1
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged)
and
func textFieldDidChange(_ textField: UITextField) {
}
斯威夫特2.2
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
and
func textFieldDidChange(textField: UITextField) {
//your code
}
objective - c
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
和textFieldDidChange方法是
-(void)textFieldDidChange :(UITextField *) textField{
//your code
}
也许使用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