Tom
Tom

Reputation: 197

Disable button as long as several textfields are empty

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?

Upvotes: 1

Views: 824

Answers (3)

SWAT
SWAT

Reputation: 1158

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
    }
}

Upvotes: 0

Angel F Syrus
Angel F Syrus

Reputation: 2042

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

Upvotes: 0

RajeshKumar R
RajeshKumar R

Reputation: 15778

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 }
    }
}

Upvotes: 3

Related Questions