If else statement depending on textfield

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()
    // Do any additional setup after loading the view, typically from a nib.
    appear()

}
func appear() {
    if txtfield.text?.isEmpty == true {
        label.isHidden = true

    }
    else {
        label.isHidden = false
    }}}

Hi @zalubski
Do you have any error messages? Are you sure that “appear” function is called? And by the way, there is no need to use the “==” operator since isEmpty is already boolean. You can change that string to just “if txtfield.text?.isEmpty {”

Nikita

1 Like

@nikita_gaydukov
I changed the code it still does not work.

   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
    }}}

Actually the previous version of the “if” statement was better, sorry. Force unwrapping isn’t really a good thing in your case.

Try to put breakpoints in each line of the appear() and viewDidLoad functions and see what is going on. This should help to understand a problem.

For me, this worked (Xcode 9b), so check whether your outlets are connected properly.

I prefer to check for an empty string as that makes intentions clearer.
if txtField.text == ""

If you want the label to appear when the user is typing text into the textfield, you can create
@IBAction func txtFieldChanged(_ sender: UITextField) { toggleLabelVisibility() }
and connected it to the textField’s ‘Did End on Editing’ action.

1 Like