How to determine which button is pressed in Objective-C?

I am a new iPad developer.

I created UIButton programmatically, in which I want to determine that the user clicked on which button and in accordance with this I want to do some action.

How do I determine this?

Here is my code snippet:

for(int i=0;i<[_array count];i++)
    {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.tag=count;
        [button addTarget:self 
                   action:@selector(aMethod:)
         forControlEvents:UIControlEventTouchDown];

        button.backgroundColor=[UIColor redColor];
        [button setTitle:@"Show View" forState:UIControlStateNormal];
        button.frame = CGRectMake(xpos, 270.0, 200.0, 150.0);

        [self.view addSubview:button];            
    }

This is what I am doing now: I thought I would assign an account to each button, and I will pass this account on to the button click method. Is that a good idea? Is there another way?

When I click the button, I call aMethod:

-(void)aMethod:(id)sender{
    NSLog(@"btn clicked");

}

Any help would be appreciated!

+3
source share
1 answer
-(void)aMethod:(UIButton*)sender{
    NSLog(@"btn clicked %d", sender.tag);

}
+16
source

All Articles