Search code examples
iosswift3delegatestextfieldis-empty

If else statement depending on textfield (swif3)


I would like my code to simply display a label if and only if there is text in the textfiled if there is no text the label should be hidden. Thats it. My code below does not do what I have described above.

   import UIKit
class ViewController: UIViewController {

  @IBOutlet var label: UILabel!
  @IBOutlet var txtfield: UITextField!
 override func viewDidLoad() {
super.viewDidLoad()
appear()

  }
   func appear() {

if (txtfield.text?.isEmpty)! {
    label.isHidden = true

}
else {
    label.isHidden = false
}}}

Solution

  • Use the code below .

     override func viewWillAppear(_ animated: Bool)
        {
            textChanged(txtField)
        }
    
        func textChanged(_ textField: UITextField) {
    
            if textField.text == ""
            {
                textField.isHidden = true
            }
            else
            {
                textField.isHidden = false
            }
            print("Hello")
        }
    
        override func viewDidLoad()
        {
            super.viewDidLoad()
            txtField.addTarget(self, action: #selector(textChanged(_:)),for: .allEvents)
        }
    
    • func textChanged will hide your textField if it is empty .
    • Adding it to viewWillAppear will check textField at the screen appearing time .
    • In viewDidLoad target (textChanged) is added to textField for every events .