iPhone: Pass a value to a method called via @selector()
I want to pass a variable to he buttonEvent method in the开发者_Go百科 selector.
[button addTarget:messageTableViewController action:@selector(buttonEvent) forControlEvents:UIControlEventTouchUpInside];
How does one do this, say if the variable is uid?
the method signature is -(void)buttonEvent:(NString *)uid;
Store all of your buttons in an array.
Store the arguments you want to pass in another array.
Use the -(IBAction) myAction:(id)sender, and look for your button in the button array (indexOfObject)
Use that index to look up the value you want from your array of uid strings and proceed.
An alternative is to set the .tag integer value for each UIButton to be an index, again into that array of uids.
First, you need to include the colon in the @selector call:
[button addTarget: messageTableViewController action: @selector(buttonEvent:) forControlEvents: UIControlEventTouchUpInside];
Second, you can't do exactly what you want. The argument passed to buttonEvent: will always be the actual control that was touched. You can use that control to figure out what to do next (ie, either use it directly, or set its tag and use that).
The target-action mechanism will send the sender of the action to the argument of the selector, in your case, the button that was pressed. I don't think there's any way around it.
You will probably want to associate your uid with the button (in a NSDictionary, for example), and fetch it in the action method, for example:
- (void)buttonEvent:(id)sender
{
NSDictionary *dict = self.buttonToUidDict;
NSString *uid = [dict valueForKey:sender];
}
精彩评论