简体   繁体   中英

Toggling UITextField to show and hide in Swift

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. 用户名文本字段仍然显示何时切换登录

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

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

Updated for Swift :

Used below simple code :

// UIButtonOutlet

@IBOutlet var confirmPassTextField: UITextField!
@IBOutlet var confirmPassButton: UIButton!

//IBAction Method

@IBAction func actionOnConfirmButton(_ sender: Any) {
    if (confirmPassTextField.isSecureTextEntry == true){
        confirmPassTextField.isSecureTextEntry = false
        confirmPassButton.setImage(UIImage(named: "show_pass"), for: .normal)
    }else{
        confirmPassButton.setImage(UIImage(named: "hide_pass"), for: .normal)
        confirmPassTextField.isSecureTextEntry = true
    }
}

Note: "show_pass" and "hide_pass" - UIImage Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM