How to create multiple buttons dynamically and handle their separate events? + iPhone SDK

12,510

Solution 1

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];

Solution 2

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.

Solution 3

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

Share:
12,510
Sreelal
Author by

Sreelal

Updated on June 14, 2022

Comments

  • Sreelal
    Sreelal almost 2 years

    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