Reputation: 5651
When an IBAction is called:
-(IBAction) onClick1: (id) sender;
What is passed in the sender? Since it's hooked up through the IB, I'm not really sure. My question is how to get the text of the button to be the passed object (NSString most likely) so that I could call it inside the action implementation.
-(IBAction) onClick1: (id) sender {
NSLog(@"User clicked %@", sender);
// Do something here with the variable 'sender'
}
Upvotes: 30
Views: 88001
Reputation: 15981
To fetch the text from the button:
NSLog(@"Date::%@",[btn titleForState:UIControlStateNormal]);
Upvotes: 1
Reputation: 6708
-(IBAction)onClick:(id) sender {
UIButton *btn = (UIButton *)sender;
//now btn is the same object. And to get title directly
NSLog(@"Clicked button: %@",[[btn titleLabel] text]);
}
Upvotes: 14
Reputation: 2361
Simply write the following code
-(IBAction) getButtonTitle:(id)sender
{
UIButton *button = (UIButton *)sender;
NSString *buttonTitle = button.currentTitle;
NSLog(@"Button Title %@",buttonTitle);
}
Thats it... you have done!!!
Upvotes: 10
Reputation: 21
You can just use the following to get the button label and determine which one was clicked:
NSLog(@"Clicked button: %@",[[sender titleLabel] text]);
To answer your question, the id is the object from the IB.
Upvotes: 2
Reputation: 6628
The sender
should be the control which initiated the action. However, you should not assume its type and should instead leave it defined as an id
. Instead, check for the object's class in the actual method as follows:
- (IBAction)onClick1:(id)sender {
// Make sure it's a UIButton
if (![sender isKindOfClass:[UIButton class]])
return;
NSString *title = [(UIButton *)sender currentTitle];
}
Upvotes: 60
Reputation: 40515
Sender should be defined as type id, not int or NSString. The sender is the actual object that's calling the method; if you hooked it up to a button, it will be a UIButton, if it's a text field, a UITextField. You can use this to get information from the control (for example the text field's current string value), or compare it to an IBOutlet instance variable if you have multiple controls hooked up to the same action method.
Upvotes: 2
Reputation: 19251
It's actually:
-(IBAction) onClick1: (id) sender {
NSLog(@"User clicked %@", sender);
// Do something here with the variable 'sender'
}
sender
is not a NSString
, it's of type id
. It's just the control that sent the event. So if your method is trigged on a button click, the UIButton
object that was clicked will be sent. You can access all of the standard UIButton
methods and properties programmatically.
Upvotes: 25