I have 3 UISwitches in my View Controller and each one identifies gender ("Woman, Male, No Gender") that user has to choose.
The behavior I would like to implement is that, when the user taps on a switch to select the gender, the others two have to be disabled simultaneously.
And once the switch is selected, the "Create Profile" button is activated. (screenshots attached)
I’m not able to implement the if condition (or alternatively a switch condition)to do that.
Please help.
This is the code I implemented:
- (IBAction)checkGenderSwitch:(id)sender {
if ([self.femaleGenderSwitch isOn] && (![self.maleGenderSwitch isOn] && ![self.noGenderSwitch isOn])) {
[self enableCreateProfileButton];
} else if ([self.maleGenderSwitch isOn] && (![self.femaleGenderSwitch isOn] && ![self.noGenderSwitch isOn])) {
[self enableCreateProfileButton];
} else if ([self.noGenderSwitch isOn] && (![self.femaleGenderSwitch isOn] && ![self.maleGenderSwitch isOn])) {
[self enableCreateProfileButton];
}else{
[self disableCreateProfileButton];
}
}
Thanks.
3
Answers
Let’s reformulate your need:
Every time you change a switch value, you do (in pseudo code):
Which could be translated in:
only... isOn
? What about putting them into aNSArray
, and count the number ofisOn
? That should do the trick no?only... isOn
is forcount = 0 where isOn == true
.Which could be then coded:
Now, if you want that when you switchOn a Switch, you switchOff the other two (if needed), which in our case would only be one, it can be done with:
As has been said in a comment, the disablement requirement is wrong. All three switches need to be enabled at all times. The rule should be simply that only one switch at a time can be on.
The key here is that when you tap a switch, and the IBAction method is called, the
sender
is that switch.So just keep a list references to all three switches and if the sender is now
on
, cycle thru the list and turn off each switch that is not the sender.(Or use a three part UISegmentedControl which does all this for you automatically; it lets the user choose exactly one of three.)
I would use the
tag
property ofUIView
for your three switches, giving each of the three its own, unique tag value: for instance, 0, 1, 2. (You can set that up in Interface Builder, or in code — whichever you prefer.) This makes it trivial to distinguish the three switches.Then, create one extra property,
genders
, an array of your three switches:In
-viewDidLoad
set that up:Finally, you can simplify your logic in your action method like this: