0

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)
    }
}
Zion
  • 1,562
  • 13
  • 32
Blue Moose
  • 125
  • 1
  • 15

2 Answers2

1

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?

Zion
  • 1,562
  • 13
  • 32
  • that did it! I need to learn more about the textfielddidchange. If I were to add multiple text fields would I just repeat this process for each field made or is there a way to add up the combination of all of them? – Blue Moose Dec 31 '17 at 03:10
  • For multiple text fields, you can add the same target to all the text fields like in my example. Then in the textFieldDidChange function, you can check which text field changed with `if textField == nicknameField { do something } – Zion Dec 31 '17 at 03:15
  • @LeoDabus I couldn't get that to work for the textfields. I must have been entering it in the wrong area. – Blue Moose Dec 31 '17 at 03:30
  • @BlueMoose add a switch `switch textField { case nicknameField: // do something to nicknameField` – Leo Dabus Dec 31 '17 at 03:36
0

Use delegate to be notify of any change. Delegates is a key part of iOS development and Apple's framework.

class TableViewController: UITableViewController, UITextFieldDelegate {

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

    override func viewDidLoad() {
        super.viewDidLoad()

        saveBtnHidden()    

        nicknameField.delegate = self   
    }


    func textFieldDidChange(_ textField: UITextField) {
        saveBtnHidden() 
    }
 // More of your source code below...