views:

13

answers:

1

With a loop I add UIImageView to a UIScrollView i need to add an extra parameter addTarget so when i click i can log the index.

[imageButton addTarget:self action:@selector(buttonPushed:) 
      forControlEvents:UIControlEventTouchUpInside];


-(IBaction) buttonPushed: (int) index
{
    NSLog(@"%d",index);
}

How do i achieve this?

A: 

When you add a target, the method being call can either have no arguments (e.g. buttonPushed) or have one (buttonPushed:) which is the control sending the event (in this case your button). If you want an index, or any other value, you need to set it on the button sending the event. For example, when you setup the buttons:

myButtons = [NSArray arrayWithObjects:myFirstButton, mySecondButton, nil];
[myFirstButton addTarget:self action:@selector(buttonPushed:) 
  forControlEvents:UIControlEventTouchUpInside];
[mySecondButton addTarget:self action:@selector(buttonPushed:) 
  forControlEvents:UIControlEventTouchUpInside];

and implement your action as

- (IBaction)buttonPushed:(UIButton *)button
{
    NSLog(@"%d",[myButtons indexOfObject:button]);
}
Mo