How to implement addTarget property in UIButton

I have a function (e.g. function1 ) where I have a button and an object called auxiliarStruct, and I have this line:

[btn addTarget:self action:@selector(userSelected:) forControlEvents:UIControlEventTouchUpInside]; 

But in @selector (userSelected) I need to pass as parameters the object needed in this function, but I don’t know how to implement it. I declared this 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 call a function declared as follows:

 -(void)userSelected:(id)sender{ //CODE } 

I have an object of this class called auxiliarStruct, and this is what I need. I tried using

 [btn addTarget:self action:@selector(**userSelected:auxiliarStruct**)forControlEvents:UIControlEventTouchUpInside]; 

but it doesn’t work. Can someone help me? Thanks.

ps: sorry for my english i know it bad

+7
source share
3 answers

You can pass an object (UIButton*) only as a parameter using the addTarget @selector method. You can set the UIButton tag and use it for the called function. You can find any alternatives for sending string values.

Use the code below to pass the tag using the 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); } 
+18
source

I do not know if you can add parameters to the button action, I have never come across such a method.

The closest we've done is to select different tags for the buttons and separate the actions according to the tags.

In any case, this is not quite the answer to your question, but I would suggest using the class property instead of sending the parameter as an alternative. For example:

  • you press the button and you want to send the value "test" to your selector. Instead of sending a "test", you set the properties of the "test" class for this, and in your selector you read it from there. I do not know if this meets your needs 100%, but I believe that this is an option.

You are raising an interesting question. I will try and look at it in case I need it sometimes, and if I find anything, I will update my answer

[edit] Apparently, you're not the only one asking this question: How do I pass a parameter to this function? In this case, there was also no standard solution and a tag was used.

+3
source

The event will send the button as a parameter, therefore:

  -(void)userSelected:(id)sender { UIButton *button = sender; ... } 
+1
source

All Articles