Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to programmatically 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: 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.

like image 357
just_another_coder Avatar asked Apr 15 '10 14:04

just_another_coder


2 Answers

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]); } 
like image 119
Jason Coco Avatar answered Oct 09 '22 22:10

Jason Coco


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;    ... } 
like image 33
kennytm Avatar answered Oct 09 '22 20:10

kennytm