Toggling UITextField to show and hide in Swift

Darin Wilson picture Darin Wilson · Oct 11, 2016 · Viewed 11.2k times · Source

I'm trying to hide a username textfield when toggling over to login from register and show it again when toggling back. I'm programming the UI in and I would like to figure out how you can hide a textfield, I'm new to swift and I think there are two places I could insert code to hide the username textfield. If not please tell me, Thanks!

Image of what I am trying to hide. Username Textfield Still Showing when login is toggled

Here in the UISegmentedControl

lazy var loginRegisterSegmentControl: UISegmentedControl = {
        let sc = UISegmentedControl(items: ["Login", "Register"])
        sc.translatesAutoresizingMaskIntoConstraints = false
        sc.tintColor = UIColor.white
        sc.selectedSegmentIndex = 1
        sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
        return sc
    }()

Or here in the HeightAnchor Change

nameTextFieldHeightAnchor?.isActive = false
        nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: loginRegisterSegmentControl.selectedSegmentIndex == 0 ? 0 : 1/3)
        nameTextFieldHeightAnchor?.isActive = true

Answer

KSigWyatt picture KSigWyatt · Oct 11, 2016

Use this to set when you want the UITextField hidden or visible depending on your application structure

You can do it this way to make the field visible:

myTextField.isHidden = false

and this way to make it hidden:

myTextField.isHidden = true