Reputation: 6362
I have a handful of UIButtons that when pressed fire the method, (IBAction)buttonPressed:(id)sender. Right now I have a document label set for each (btnPlay, btnStop, btnPause), but I don't believe I can access this in Objective C. Is there something I can set in xcode that acts as a variable so when buttonPressed() is fired I know which button (btnPlay, btnStop, or btnPause) fired the event?
Upvotes: 2
Views: 244
Reputation: 10712
You should change your IBAction to something like the below
-(IBAction)buttonPressed:(UIButton *)button {
if([button.titleLabel.text isEqualToString:@"Start"]){
//Do Stuff
}
}
In this way you can access the sender as a button directly with no issues or type casting required, you can then use the isEqualToString
method to check the title of the button and run code inside the if statement.
You might also like to consider using the tag
property which pretty much all Interface Objects have.
if(button.tag == 1){
//Do Stuff
}
Switch statements are also a nice clean way of handling different events..
switch (button.tag) {
case 1:
// Do Something
break;
default:
// Do Default Action
break;
}
Upvotes: 2
Reputation: 31
you can define which method has to be called when the button pressed after @selector in this case playVideo method.
[videoButton setTitle:@"play video" forState:UIControlStateNormal];
[videoButton setBackgroundImage:nil forState:UIControlStateNormal];
[videoButton addTarget:self action:@selector(playVideo:)forControlEvents:UIControlEventTouchUpInside];
Upvotes: 1
Reputation: 16316
Every UIButton
has a titleLabel
property, which is a UILabel
. Check sender.titleLabel.text
and compare it against the three strings.
Alternatively, you can also assign each button a tag (generally an integer), either through the Attributes Inspector in Xcode, or using the tag
property in code. Then check sender.tag
in your action method.
Upvotes: 0
Reputation: 60110
That's what the sender
argument is there for - you can compare it against each of your buttons in a chain of if
statements to see which one sent that message.
Upvotes: 0