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

Ios 只要几个文本字段为空,则禁用按钮,ios,swift,xcode,uitextfield,Ios,Swift,Xcode,Uitextfield,只要文本字段为空,我有以下代码来禁用按钮: func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)

只要文本字段为空,我有以下代码来禁用按钮:

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 { $0.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 { $0?.text == "" }
    if !filteredArray.isEmpty {
        button.isHidden = true
    } else {
        button.isHidden = false
    }
}