skip to Main Content

Question 1. How can I use a switch to hide/show a text field in Swift?

Question 2. How can I make the text field area be hidden and shown dynamically?
btw: I’m working on Swift storyboard.

My problem was caused by a hidden object, and it was solved after deleting it.
Thanks, everyone!

2

Answers


  1. First take Outlet of textfield. Then show and hide textfield on switch’s ON & OFF State.

    Login or Signup to reply.
  2. @IBOutlet weak var stateSwitch:  UISwitch!
    @IBOutlet var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()     
        stateSwitch.addTarget(self, action: #selector(stateChanged), for: .valueChanged)
    }
    
    func stateChanged(switchState: UISwitch) {
        //Single line code
        //textField.isHidden = !switchState.isOn
    
        //Multi line code
        if switchState.isOn {
           textField.isHidden = false
        } else {
            textField.isHidden = true
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search