hanumanDev
hanumanDev

Reputation: 6614

How to have a method for each UIButton in an array

I have an array of UIButtons in the following code. Problem I'm having is that I need a unique method associated with each button. At the moment any button that's pressed all use the action:@selector(buttonPressed:)

I'm stuck on how to have a method hooked up to each button.

 // Create buttons
        NSMutableArray* buttonArray = [NSMutableArray array];
        NSArray * myImages = [NSArray arrayWithObjects:@"category-cafe-unsel.png", @"category-food-unsel.png", @"category-clothing-unsel.png", @"category-health-unsel.png", @"category-tech-unsel_phone.png" , @"category-tech2-unsel.png", @"catefory-theatre-unsel.png", @"category-travel-unsel.png", nil];

        // only create the amount of buttons based on the image array count
        for(int i = 0;i < [myImages count]; i++)
        {
            // Custom UIButton
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

            [btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
            [btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];

            [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [buttonArray addObject:btn];
        }

thanks for any help

:)

Upvotes: 0

Views: 143

Answers (3)

Hemang
Hemang

Reputation: 1234

Use following code:

-(void)buttonPressed:(UIButton*)sender
{
    UIButton *btn = sender;
    for(int i = 0;i < [myImages count]; i++)
    {
       if (i == [btn tag]) {

       //Your code

       break;
       }
     }
}

It's completly working fine. When you'll get Tag value, you can perform operations as per tag value.

Thanks,

Hemang.

Upvotes: 2

Roland Keesom
Roland Keesom

Reputation: 8288

Best option is to use same method for all buttons.For that you should use tags. So each button has its own tag.

btn.tag = i;

Here tag number will be used for differentiating which button was called.

And then in the method you can get the tags, this can also be done with a switch-statement:

-(void)buttonPressed:(UIButton*)sender
{
    if( sender.tag == 1 ){

    } else {

    }
}

Upvotes: 4

Hermann Klecker
Hermann Klecker

Reputation: 14068

[btn addTarget:self action:@selector(NSSelectorFromString([NSString stringWithFormat:@"button%d", i])) forControlEvents:UIControlEventTouchUpInside];

And the corresponding actions would be:

-(void)button1:(UIButton*)sender
-(void)button2:(UIButton*)sender
-(void)button3:(UIButton*)sender
-(void)button4:(UIButton*)sender

and so forth.

However, alternatively consider having one action method only and using tags to separate the buttons within the action method.

Upvotes: 1

Related Questions