views:

596

answers:

4

I want to programatically add multiple UIButtons to a view - the number of buttons is unknown at compile time.

I can make one or more UIButton's like so (in a loop, but shorted for simplicity):

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Button x" forState:UIControlStateNormal];
button.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);
[view addSubview:button];

Copied/Edited from this link: http://stackoverflow.com/questions/1378765/how-do-i-create-a-basic-uibutton-programmatically

But how do I determine in buttonClicked: which button was clicked? I'd like to pass tag data if possible to identify the button.

+2  A: 

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;
   ...
}
KennyTM
Thank you very much!
just_another_coder
A: 

UIButton has a tag property. Use that and in your buttonClicked method, you can check the button that was clicked based on it's tag. Might want to keep constants around for what button is what.

Shadow
+1  A: 

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]);
}
Jason Coco
Thank you very much!
just_another_coder
A: 

For each of your buttons set an appropriate tag, and then refer to the tag in your action. i.e.

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
...
button.tag = 1
[view addSubview:button]; 

You can easily set the tag based on the index of your iteration, if you're creating buttons in a loop. And then in your action:

- (void)aButtonWasTapped:(UIButton *)source {
    if( source.tag == 1 ) {
        // etc
    }
}
dannywartnaby