2

Now I am creating a IPhone App. I need to create multiple buttons dynamically and handle their corresponding events separately. Can each button events behave separately, or can I send a variable or an object to a method and depending upon that value differentiate the button behavior. Can anybody point me to how to do that?

Please Help,

Syam

Rich Seller
  • 83,208
  • 23
  • 172
  • 177
Sreelal
  • 785
  • 3
  • 13
  • 15

3 Answers3

7

You should check out the UI Catalog sample in the iPhone SDK. It has examples of programmaticaly creating all the UI elements.

I don't believe you can pass an argument to the function that's called when a button is triggered, so you would need a separate function for each button. However these could be lightweight functions that call another with a param.

To manually create a button and set its action you would do something like:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 170, 150.0, 30.0);
[button setTitle:@"My Button" forState:UIControlStateNormal];
[button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
Andrew Grant
  • 58,260
  • 22
  • 130
  • 143
5

When a button calls an IBAction (which would be the selector you pass in), it also passes a pointer to the button being presed in the :(id)sender argument you normally have:

- (IBAction) doSoemthing:(id)sender

So you can just figure out based on the button passed in, what you want to do. Either by creating a map based on all of the button addresses, or by having all UIButtons you use be subclasses of UIButton where you insert some kind of custom ID and look that up when doSomething: is hit.

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
2

You can use the tag property of UIButton programmatically and access the tag. This is easier than subclassing.

Here is an example: Detecting which UIButton was pressed in a UITableView

Community
  • 1
  • 1