只要多个文本字段为空,请禁用按钮 [英] Disable button as long as several textfields are empty

查看:122
本文介绍了只要多个文本字段为空,请禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

它工作正常,但是现在我有3个文本字段,如果所有文本字段都不为空,我希望仅启用按钮.到目前为止,一旦填写了一个文本字段,就会启用该按钮.

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?

推荐答案

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

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

这篇关于只要多个文本字段为空,请禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆