Tono Nam
Tono Nam

Reputation: 36048

pass parameter through selector

there is a similar question in here but for some reason I cannot make it work.

I am creating a lot of buttons so I am creating them dynamically with code. so the following code creates a button that when on touchdouwn it executes the aMethod:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
           action:@selector(aMethod)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(40.0, 200.0, 170.0, 40.0);
[self.view addSubview:button];

-(void) aMethod{
   //code
}

in the aMethod I want to know wich button was pressed because many buttons point to that method. as a result I need my aMethod to look like:

-(void) aMethod:(id) sender{
   //code
}

if I change the aMethod then I have to change the selector for:

[button addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchDown];

when I click on the button I get an error. so from reading the post on the first link that I posted I found out that the selector will pas a button so I tried changing aMethod to:

-(void) aMethod:(UIButton*) sender{
       //code
    }

and I still get an error. How can I pass the button with the selector?

Upvotes: 1

Views: 372

Answers (1)

mattacular
mattacular

Reputation: 1889

I don't quite understand what you're asking but ID is an arbitrary object that represents some other object (think dynamic typing?). Don't change the datatype on your selector method from ID to anything else.

If it is a method that is fired by UIButtons, then you access the button like this:

-(void) aMethod:(id)sender {
UIButton *pressedButton = (UIButton *)sender;
}

Now you have the UIButton object for whatever button triggered the selector method to be fired.

One way to tell which button fired the selector, give them tags then inspect the tag in your aMethod:. After making a pointer to the button object using the code above you'll have access to pressedButton.tag

Upvotes: 1

Related Questions