Reputation: 1193
I have the following IBAction that is linked to several switch in my application. I would like to figure out which switch is clicked. Each UISwitch has a specific name. I want that name.
- (IBAction)valueChanged:(UISwitch *)theSwitch { //Get name of switch and do something... }
Upvotes: 1
Views: 717
Reputation: 6844
The IBAction passes a pointer to the switch that performed the action. You can get any property off of it.
To compare switches:
- (void)valueChanged:(UISwitch *)theSwitch {
if ([theSwitch isEqual:self.switch1]) {
NSLog(@"The first switch was toggled!");
}
else if ([theSwitch isEqual:self.switch2]) {
NSLog(@"The second switch was toggled!");
}
else {
NSLog(@"Some other switch was toggled!");
}
}
Upvotes: 2
Reputation: 77291
UISwitch doesn't have a name property. But you can subclass it and add a name property to the subclass. Then create switches from the subclass instead of UISwitch and give them a name when you init them.
@class MySwitch : UISwitch
@property (nonatomic, retain) NSString* name;
@end
Then the event handler can access them name string:
- (IBAction)valueChanged:(MySwitch *)theSwitch {
NSLog(@"switch %@ value changed", theSwitch.name);
}
But I think the better answer is to use the tag field already there and use integer tags to identify the switches rather than a string. You can create enumeration constants in your code to name the tag values:
enum { SomeSwitch = 1, AnotherSwitch = 2, MainSwitch = 3 } _SwitchTags;
The best answer is the one @Moxy mentioned to compare the switch's pointer to your controller's properties to figure out which switch changed. That's what I do in my code. Tags and names are too error prone in the long run.
Upvotes: 0
Reputation: 4212
You can either use tags:
When you create the switches you need to set their tags.
- (IBAction)valueChanged:(UISwitch *)theSwitch {
switch(theSwitch.tag){
case 0:
{
//things to be done when the switch with tag 0 changes value
}
break;
case 1:
{
//things to be done when the switch with tag 0 changes value
}
break;
// ...
default:
break;
}
}
Or check if the switch is one of your controller properties
- (IBAction)valueChanged:(UISwitch *)theSwitch {
if(theSwitch == self.switch1){
//things to be done when the switch1 changes value
} else if (theSwitch == self.switch2) {
//things to be done when the switch2 changes value
}// test all the cases you have
}
Upvotes: 2
Reputation: 472
I don't thank you can get the name of that switch. You could tag each of the switches, and use that tag to determine the name of the switch.
Upvotes: 0