如何在UITextfield数据为空或填充时禁用/启用按钮?

时间:2017-01-02 00:04:55

标签: ios swift

Output Console

这是我的功能。如您所见,当文本字段为空(或为零)时,我能够在控制台中收到消息,并且该按钮被禁用。但是,当数据输入我的文本字段时,我没有收到回复。如果有人可以帮我解决这个或类似的解决方案,我将非常感激。

func logicDataCheck() {
    let textfield: Array<Bool?> = [lastNameTextField.text?.isEmpty, phoneNumberTextField.text?.isEmpty, firstNameTextField.text?.isEmpty]

    if (textfield[0]! || textfield [1]! || textfield [2]!)
    {
        print("Textfield is empty")
        continue_Button.isEnabled = false
        continue_Button.alpha = 0.5
    }
    else 
    {
        if (textfield[0]! || textfield [1]! || textfield [2]!) {
            print("Textfield is full")
            continue_Button.isEnabled = true
            continue_Button.alpha = 1
        }
    }
}

2 个答案:

答案 0 :(得分:2)

viewDidLoad中,您可以添加以下行:

configureTextFields()
// you'll need to call updateTextField() when the view loads the first time.
// After the configureTextFields() adds targets, it'll get called when editing changes
updateTextField()

另外,添加以下方法:

func configureTextFields() {
    // create an array of textfields
    let textFieldArray = [firstNameTextField, lastNameTextField, phoneNumberTextField]

    // configure them...
    for textField in textFieldArray {
        // make sure you set the delegate to be self
        textField?.delegate = self
        // add a target to them
        textField?.addTarget(self, action: #selector(ViewController.updateTextField), for: .editingChanged)
    }
}

// this is the target that gets called when editing changes
func updateTextField() {
    // create an array of textFields
    let textFields = [firstNameTextField, lastNameTextField, phoneNumberTextField]
    // create a bool to test if a textField is blank in the textFields array
    let oneOfTheTextFieldsIsBlank = textFields.contains(where: {($0?.text ?? "").isEmpty})
    if oneOfTheTextFieldsIsBlank {
        continueButton.isEnabled = false
        continueButton.alpha = 0.5
    } else {
        continueButton.isEnabled = true
        continueButton.alpha = 1.0
    }
}

您需要使ViewController采用UITextFieldDelegate协议。你可以这样做:

class ViewController: UIViewController, UITextFieldDelegate {
// the code inside your view controller
}

以下是指向demo I created on GitHub

的链接

答案 1 :(得分:0)

尝试这个

func logicDataCheck() {
    let textfield: Array<Bool> = [lastNameTextField.text?.isEmpty, phoneNumberTextField.text?.isEmpty, firstNameTextField.text?.isEmpty]

    if (textfield[0] || textfield [1] || textfield [2])
    {
        print("Textfield is empty")
        continue_Button.isEnabled = false
        continue_Button.alpha = 0.5
    }
    else 
    {
        print("Textfield is full")
        continue_Button.isEnabled = true
        continue_Button.alpha = 1
    }
}