Search code examples
swiftbuttontextfieldhiddenvisible

textfield not empty show save button in Swift


My save button is hidden with the function saveBtnHidden() in the code below. However, the save button won't reappear when text is typed into the text field. I have tried multiple solutions similar to this. Every time that I type into the text field, the save button just won't show up.

import UIKit

class TableViewController: UITableViewController, UITextFieldDelegate {

    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet var nicknameField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        saveBtnHidden()      
    }

    func saveBtnHidden() {
        if (nicknameField.text?.isEmpty ?? true) {
            // is empty
            saveBtn.isHidden = true
        } else {
            saveBtn.isHidden = false
        }
    }

    @IBAction func saveBtnPressed(_ sender: Any) {
        performSegue(withIdentifier: "nextPage", sender: nil)
    }
}

Solution

  • You are getting this error because your function saveBtnHidden() is only called once in viewDidLoad(). It does not get called again when the text in your text field changes. To detect when text changes, you will need to add a target to your text field that calls a function when it changes (.editingChanged) like this:

    nicknameField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    

    Then in the textFieldDidChange call your saveBtnHidden() function:

    func textFieldDidChange(_ textField: UITextField) {
        saveBtnHidden() 
    }
    

    Code adapted from: How do I check when a UITextField changes?