D. Finna D. Finna - 3 months ago 9
Swift Question

Hide buttons when textfield equals nil and show when not nil

With my code the buttons are hiding when the viewcontroller is showing because the textfields are empty. The buttons should however show when the textfields are not empty anymore. The buttons are not showing with my code - what am I doing wrong?

let allInputValues = nameInput.text! + middleInput.text! + surnameInput.text!

if allInputValues == "" {
nextButton.hidden = true
finishButton.hidden = true
} else {
nextButton.hidden = false
finishButton.hidden = false
}


Hope you can help me

Answer

Set up your view controller as a textField delegate. Then use textFieldDidEndEditing() for each textField to run your check and either keep the button hidden or show the button.

class MyViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        nextButton.hidden = true
        finishButton.hidden = true

        nameInput.delegate = self
        middleInput.delegate = self
        surnameInput.delegate = self
    }

    func textFieldDidEndEditing(textField: UITextField) {
        let allInputValues = nameInput.text! + middleInput.text! + surnameInput.text!

        if allInputValues == "" {
            nextButton.hidden = true
            finishButton.hidden = true
        } else {
            nextButton.hidden = false
            finishButton.hidden = false
        }
    }
}