Disable button as long as several textfields are empty

浪尽此生 提交于 2020-01-21 19:25:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!