I currently have login / register button working with segmented controls. I am trying to use the button login to use the handleLogin function, and the register button to use the handleRegister function. I currently try to call these functions this way, but no luck. My code is below:
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch loginRegisterSegmentedControl.selectedSegmentIndex {
case 0:
nameTextField.isHidden = true
universityTextField.isHidden = true
universityDropDown.isHidden = true
loginRegisterButton.setTitle("Login", for: UIControlState())
loginRegisterButton.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
case 1:
universityTextField.isHidden = false
nameTextField.isHidden = false
loginRegisterButton.setTitle("Register", for: UIControlState())
loginRegisterButton.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
default:
break;
}
}
First of all, you can write separate function for changing interface according to selectedIndex
of the UISegmentedControl
. Also, you need only one Target
to perform particular action. So, before adding a target you need to remove other all targets. Else you will get multiple actions at a time of pressing the loginRegisterButton
.
func changeInterfaceAccoringto(_ index:Int){
/*Remove all targets before add*/
loginRegisterButton.removeTarget(nil, action: nil, for: .allEvents)
switch index {
case 0:
nameTextField.isHidden = true
universityTextField.isHidden = true
universityDropDown.isHidden = true
loginRegisterButton.setTitle("Login", for: UIControlState())
loginRegisterButton.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
case 1:
universityTextField.isHidden = false
nameTextField.isHidden = false
loginRegisterButton.setTitle("Register", for: UIControlState())
loginRegisterButton.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
default:
break;
}
}
call changeInterfaceAccoringto
at indexChanged
like as below,
@IBAction func indexChanged(_ sender: UISegmentedControl) {
changeInterfaceAccoringto(loginRegisterSegmentedControl.selectedSegmentIndex)
}
For changing Interface at ideal you need to call changeInterfaceAccoringto
in method viewDidLoad
like as below,
override func viewDidLoad() {
super.viewDidLoad()
/*Change UISegmentedControl selected index at ideal if you want*/
//loginRegisterSegmentedControl.selectedSegmentIndex = 1
changeInterfaceAccoringto(loginRegisterSegmentedControl.selectedSegmentIndex)
}
Let me know is that you need?