Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to a UIButton action

Tags:

ios

uibutton

I want to pass a variable to a UIButton action, for example

NSString *string=@"one";
[downbutton addTarget:self action:@selector(action1:string)
     forControlEvents:UIControlEventTouchUpInside];

and my action function is like:

-(void) action1:(NSString *)string{
}

However, it returns a syntax error. How to pass a variable to a UIButton action?

like image 543
issac Avatar asked Feb 04 '09 07:02

issac


3 Answers

Change it to read:

[downbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];

I don't know about the Iphone SDK, but the target of a button action probably receives an id (usually named sender).

- (void) buttonPress:(id)sender;

Within the method call, sender should be the button in your case, allowing you to read properties such as it's name, tag, etc.

like image 50
diciu Avatar answered Oct 12 '22 23:10

diciu


If you need to distinguish between multiple buttons, then you could mark your buttons with tags like this:

[downbutton addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
downButton.tag = 15;

In your action delegate method you can then handle each button according to its previously set tag:

(void) buttonPress:(id)sender {
    NSInteger tid = ((UIControl *) sender).tag;
    if (tid == 15) {
        // deal with downButton event here ..
    }
    //...
}

UPDATE: sender.tag should be a NSInteger instead of a NSInteger *

like image 41
leviathan Avatar answered Oct 13 '22 00:10

leviathan


You can use associative references to add arbitrary data to your UIButton:

static char myDataKey;
...
UIButton *myButton = ...
NSString *myData = @"This could be any object type";
objc_setAssociatedObject (myButton, &myDataKey, myData, 
  OBJC_ASSOCIATION_RETAIN);

For the policy field (OBJC_ASSOCIATION_RETAIN) specify the appropriate policy for your case. On the action delegate method:

(void) buttonPress:(id)sender {
  NSString *myData =
    (NSString *)objc_getAssociatedObject(sender, &myDataKey);
  ...
}
like image 29
Heitor Ferreira Avatar answered Oct 13 '22 00:10

Heitor Ferreira