I have a screen with several switches for the user to select an item. I want to restrict the user to only selecting one item.
I declare this variable at the top of the class, before the viewDidLoad function:
var instrumentCounter:Int = 0
I declare outlet variables for each switch:
@IBOutlet weak var guitarPlay: UISwitch!
I have a function for each switch as well (note - I have some print statements in for troubleshooting):
@IBAction func guitarSwitch(_ sender: Any) {
if self.guitarPlay.isOn == false
{
print("Top: \(instrumentCounter)")
instrumentCounter -= 1
print("Top: \(instrumentCounter)")
}
else if self.guitarPlay.isOn && instrumentCounter == 1
{
self.guitarPlay.setOn(false, animated: true)
showTooManyAlert()
print("Middle: \(instrumentCounter)")
}
else{
instrumentCounter += 1
print(instrumentCounter)
}
}
Here is the function for the alert:
func showTooManyAlert(){
let alertController = UIAlertController(title: "Alert", message:
"You can only select one instrument. Unselect another instrument to select this one.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Okay", style: .default))
self.present(alertController, animated: true, completion: nil)
}
And here's what's happening: The function for the switch works up to a certain point. I forgot to say that when the screen loads, if the user has already selected an instrument in their profile, the instrumentCounter variable increments by 1. So even before the user does anything, that variable is set to 1.
When I tap the guitar switch (which is currently off -- another switch is on), the first part of the code is skipped and the middle part executes -- the guitar switch turns off, and the alert displays. But then the first part of the code executes: instrumentCounter -= 1.
I'm at a loss as to why that is happening.
Aucun commentaire:
Enregistrer un commentaire