Reputation: 143
I've read all about UISwitches already but I cannot seem to figure them out in my situation. I have 2 UISwitches. In order for my code to work only one of them can be ON. How would I accomplish this?
So far i've tried...
MyClass.h
-(IBAction)sufSwitchChanged:(id)sender;
MyClass.m
-(IBAction)preSwitchChanged:(id)sender {
UISwitch *whichSwitch = (UISwitch *)sender;
BOOL setting = whichSwitch.isOn;
[newsPre setOn:setting animated:YES];
[techPre setOn:setting animated:YES];
}
....which worked but it made both switches ON or OFF. I just need to figure out how to prevent them from both being ON at the same time.
Upvotes: 1
Views: 1871
Reputation: 1218
Register both UISwitches to observe UIControlEventValueChanged notifications against the the other switch. Something like:
- (void)viewDidLoad { // or whatever method is appropriate
UISwitch *a = <# initialize a #>;
UISwitch *b = <# initialize b #>;
[a addTarget:self action:@selector(toggleB:)
forControlEvents:UIControlEventValueChanged];
[b addTarget:self action:@selector(toggleA:)
forControlEvents:UIControlEventValueChanged];
}
- (IBAction)toggleA:(id)sender {
[b setOn:NO animated:YES];
}
- (IBAction)toggleB:(id)sender {
[a setOn:NO animated:YES];
}
You can also set this relationship up in Interface Builder.
Upvotes: 3
Reputation: 58067
Notice how you are setting both switches to the same value here:
[newsPre setOn:setting animated:YES];
[techPre setOn:setting animated:YES];
You want to check which one is the sender and then set the other one to the opposite of setting
. To do so, you will need to set a tag on each switch, or perhaps subclass it. For more information on detecting which switch is which, see this post, which has some good information.
Upvotes: 0