RGriffiths
RGriffiths

Reputation: 5970

Creating an UIButton action with argument in iOS

I have a UIBUtton called firstButton that has the line below to add the target. However I am getting the error:

Parse issue Expected )

What is the correct syntax?

[firstButton addTarget:self action:@selector(responseAction: 1) forControlEvents:UIControlEventTouchUpInside];

- (IBAction) responseAction:(int)buttonPressed
{
NSLog(@"%d", buttonPressed);
}

Upvotes: 0

Views: 166

Answers (3)

simalone
simalone

Reputation: 2768

Use objective-c category and associative can help add almost any kind of arguments:

OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);

How to use:

UIButton+UserInfo.h:

@interface UIButton (UserInfo)

@property (nonatomic, retain) id userInfo;

@end

UIButton+UserInfo.m:

@implementation UIAlertView (UserInfo)

static char ContextPrivateKey;
- (void)setUserInfo:(id)userInfo
{
    objc_setAssociatedObject(self, &ContextPrivateKey, userInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)userInfo
{
    return objc_getAssociatedObject(self, &ContextPrivateKey);
}
@end

Apply in your code:

#import "UIButton+UserInfo.h"

[firstButton addTarget:self action:@selector(responseAction: 1) forControlEvents:UIControlEventTouchUpInside];
firstButton.userinfo = /*your argument*/; 

- (IBAction) responseAction:(int)buttonPressed
{
    NSLog(@"%@", firstButton.userinfo );
}

Hope can help you.

Upvotes: 0

Akshit Zaveri
Akshit Zaveri

Reputation: 4244

The so called "IBActions" must have one of these signatures:

-(void)action;
-(void)actionWithSender:(id)sender;
-(void)actionWithSender:(id)sender event:(UIEvent*)event;

You cannot add any other parameters. Nevertheless you can use sender (which is button1 or button2 in your case) to get the parameter:

-(void)actionWithSender:(UIButton*)sender {
   NSString* parameter;
   if (sender.tag == 1)   // button1
     parameter = @"foo";
   else                   // button2
     parameter = @"bar";
   ...
}

The above answer is from this link -> https://stackoverflow.com/a/2117146/2859764

Hope it helps.

Upvotes: 1

Samkit Jain
Samkit Jain

Reputation: 2523

You should not arguments like this. You can use tagging if you want.

Upvotes: 1

Related Questions