只要几个文本字段为空,就禁用按钮

Disable button as long as several textfields are 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
}

它工作正常,但现在我有 3 个文本字段,如果所有文本字段都不为空,我只想启用按钮。到目前为止,只要填写一个文本字段,就会启用该按钮。

我该如何调整我的代码来做到这一点?

首先,根据您的要求,您必须为每个文本字段创建插座,然后您可以启用按钮,

        @IBAction func textFieldValueChanged(_ sender: Any)
        {

        if firstTextField.text != "" && secondTextField.text != "" && thirdTextField.text != ""  {
            addButton.isEnabled = true
        } else {
            addButton.isEnabled = false
        }
        return true

并将每个文本字段与 valueChanged 事件

的上述操作连接起来

将目标添加到 .editingChanged 事件的所有文本字段,并检查是否有任何文本字段为空。如果所有文本字段都包含文本,则启用该按钮,否则禁用该按钮。

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 { [=10=].text!.isEmpty }
    }
}

嗯,我不认为接受的答案是这个问题的完美解决方案。 我建议在您的 viewDidLoad 中添加以下观察者:

NotificationCenter.default.addObserver(self, selector: #selector(validate), name: UITextField.textDidChangeNotification, object: nil)

然后定义选择器:

@objc func validate(){
    var filteredArray = [textFieldOne,textFieldTwo,textFieldThree,textFieldFour].filter { [=11=]?.text == "" }
    if !filteredArray.isEmpty {
        button.isHidden = true
    } else {
        button.isHidden = false
    }
}