Reputation: 154
I have a function (for example function1)where I have a button and an object called auxiliarStruct, and I have that line:
[btn addTarget:self action:@selector(userSelected:) forControlEvents:UIControlEventTouchUpInside];
But in @selector(userSelected) I need to pass as parameters an object needed in that function, but I don't know how implement it. I have declared that object here:
//UsersController.h
#import <UIKit/UIKit.h>
@interface UsersController : NSObject{
NSInteger *prof_id;
NSString *createTime;
NSString *fullName;
NSString *thumb;
}
@property (nonatomic) NSInteger *prof_id;
@property (nonatomic, retain) IBOutlet NSString *createTime;
@property (nonatomic, retain) IBOutlet NSString *fullName;
@property (nonatomic, retain) IBOutlet NSString *thumb;
@end
I have the called function declared like this:
-(void)userSelected:(id)sender{
//CODE
}
I have an object of this class, called auxiliarStruct and this is that I need. I tried with
[btn addTarget:self action:@selector(**userSelected:auxiliarStruct**)forControlEvents:UIControlEventTouchUpInside];
but it don't works Can anyone help me? Thanks.
ps: sorry for my english, i know it's bad
Upvotes: 8
Views: 25086
Reputation: 3667
You can only Pass a (UIButton*)
object as a parameter with addTarget @selector
method. You can set the UIButton tag and use it on the called function. You may want to find out any alternatives for sending string values.
Use the below code for passing a tag with button :
btn_.tag = 10;
[btn_ addTarget:self action:@selector(functionName:) forControlEvents:UIControlEventTouchUpInside];
The button action should look like this :
- (void) functionName:(UIButton *) sender {
NSLog(@"Tag : %d", sender.tag);
}
Upvotes: 24
Reputation: 3650
I don't know if you can add parameters to the button's action, I never encountered such a method.
The closest thing we did was to select different tags to the buttons and differentiate the actions according to the tags.
Anyway, this is not exactly an answer to your question but I would suggest as an alternative to use a class property instead of sending the parameter. For example:
You raise an interesting question though. I'll try and look into it in case I will need it too sometimes and if I find anything, I'll update my answer
[edit] Apparently you are not the only one asking this question: How can I pass a parameter to this function? In this case there was also no standard solution and the tag was used.
Upvotes: 3
Reputation: 2083
The event will send the button as parameter, so:
-(void)userSelected:(id)sender {
UIButton *button = sender;
...
}
Upvotes: 1