Search code examples
iosobjective-ciphonecocoa-touchuicontrolevents

Passing parameters to addTarget:action:forControlEvents


I am using addTarget:action:forControlEvents like this:

[newsButton addTarget:self
action:@selector(switchToNewsDetails)
forControlEvents:UIControlEventTouchUpInside];

and I would like to pass parameters to my selector "switchToNewsDetails". The only thing I succeed in doing is to pass the (id)sender by writing:

action:@selector(switchToNewsDetails:)

But I am trying to pass variables like integer values. Writing it this way doesn't work :

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i)
forControlEvents:UIControlEventTouchUpInside];

Writing it this way does not work either:

int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i:)
forControlEvents:UIControlEventTouchUpInside];

Any help would be appreciated :)


Solution

  • action:@selector(switchToNewsDetails:)
    

    You do not pass parameters to switchToNewsDetails: method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:

    1. with no parameters

      action:@selector(switchToNewsDetails)
      
    2. with 1 parameter indicating the control that sends the message

      action:@selector(switchToNewsDetails:)
      
    3. With 2 parameters indicating the control that sends the message and the event that triggered the message:

      action:@selector(switchToNewsDetails:event:)
      

    It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:

    1. set a tag property to each button equal to required index
    2. in switchToNewsDetails: method you can obtain that index and open appropriate deatails:

      - (void)switchToNewsDetails:(UIButton*)sender{
          [self openDetails:sender.tag];
          // Or place opening logic right here
      }