views:

1463

answers:

2

Hi All,

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

+3  A: 

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
+3  A: 

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
Wow....Solved my problems..... Thanks a lot Kendall........
Sreelal