问题
I have the following code to disable a button as long a textfield is empty:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if !text.isEmpty{
addButton.isEnabled = true
} else {
addButton.isEnabled = false
}
return true
}
It works fine, but now that I have 3 textfields, I want the button only to be enabled, if all textfields are not empty. So far, as soon as one textfield is filled in, the button is being enabled.
How can I adjust my code to do so?
回答1:
Add target to all textfields for .editingChanged
event, and check if any textfield is empty. If all text fields contain text enable the button else disable the button.
class TestViewController: UIViewController, UITextFieldDelegate {
let addButton = UIButton()
let textField1 = UITextField()
let textField2 = UITextField()
let textField3 = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
textField1.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
textField2.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
textField3.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
}
@objc func textChanged(_ textField: UITextField) {
addButton.isEnabled = [textField1, textField2, textField3].contains { $0.text!.isEmpty }
}
}
回答2:
As your requirement first you have to create outlet for each textfield and you can enable the button as,
@IBAction func textFieldValueChanged(_ sender: Any)
{
if firstTextField.text != "" && secondTextField.text != "" && thirdTextField.text != "" {
addButton.isEnabled = true
} else {
addButton.isEnabled = false
}
return true
And connect each textfield with the above action for valueChanged
event
回答3:
Well, I don't think the accepted answer is an elegant solution to this problem. I would suggest to add the following observer in your viewDidLoad:
NotificationCenter.default.addObserver(self, selector: #selector(validate), name: UITextField.textDidChangeNotification, object: nil)
Then define the selector:
@objc func validate(){
var filteredArray = [textFieldOne,textFieldTwo,textFieldThree,textFieldFour].filter { $0?.text == "" }
if !filteredArray.isEmpty {
button.isHidden = true
} else {
button.isHidden = false
}
}
来源:https://stackoverflow.com/questions/56166818/disable-button-as-long-as-several-textfields-are-empty