-1

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!

Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
Rasha
  • 1
  • 2

2 Answers2

1

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

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Virat
  • 45
  • 1
  • 8
1
@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
    }
}
Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
Protocol
  • 1,696
  • 13
  • 30