Add a multiple buttons to a view programmatically, call the same method, determine which button it was Add a multiple buttons to a view programmatically, call the same method, determine which button it was xcode xcode

Add a multiple buttons to a view programmatically, call the same method, determine which button it was


You could either keep a reference to the actual button object somewhere that mattered (like an array) or set the button's tag to something useful (like an offset in some other data array). For example (using the tag, since this is generally must useful):

for( int i = 0; i < 5; i++ ) {  UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];  [aButton setTag:i];  [aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];  [aView addSubview:aButton];}// then ...- (void)buttonClicked:(UIButton*)button{  NSLog(@"Button %ld clicked.", (long int)[button tag]);}


You can assign a tag to the button.

button.tag = i;

Then in -buttonClicked:, check the tag of the sender:

-(void)buttonClicked:(UIButton*)sender {   int tag = sender.tag;   ...}