0

How can I detect which UIButton has been tapped:

-(void) topScorer {

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 addTarget:self
                action:@selector(buttonClicked:)
     forControlEvents:UIControlEventTouchDown];
    [button1 setTitle:@"Button1" forState:UIControlStateNormal];
    button1.frame = CGRectMake(16, self.view.bounds.size.height*0.6, 60, 60);
    UIImage *img1 = [UIImage imageNamed:@"img1.png"];
    button1.layer.cornerRadius = 10;
    button1.layer.masksToBounds = YES;
    [button1 setImage:img1 forState:UIScrollViewDecelerationRateNormal];
    button1.tag = 1;
    [self.view addSubview:button1];

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button2 addTarget:self
            action:@selector(buttonClicked:)
      forControlEvents:UIControlEventTouchDown];
     [button2 setTitle:@"Button2" forState:UIControlStateNormal];
     button2.frame = CGRectMake(92, self.view.bounds.size.height*0.6, 60, 60);
     UIImage *img2 = [UIImage imageNamed:@"img2.png"];
     button2.layer.cornerRadius = 10;
     button2.layer.masksToBounds = YES;
     [button2 setImage:img2 forState:UIScrollViewDecelerationRateNormal];
     button2.tag = 2;
     [self.view addSubview:button2];
}


-(void) buttonClicked: (id)sender {

    // How can I detect here which button is tapped?
    // For Example, I want to do this:

    // if button1 is pressed, do something
    // if button 2 is pressed, do another thing

}
GingerHead
  • 8,130
  • 15
  • 59
  • 93
jeewan
  • 1,597
  • 5
  • 23
  • 40

2 Answers2

2

Cast your sender to a UIButton and compare the tag value.

UIButton *button = (UIButton *)sender;

if (button.tag == 1) {

} else {

}
Jean-Francois Gagnon
  • 3,141
  • 4
  • 20
  • 27
  • as always, forgot completely about type casting :D , thanks Jean – jeewan May 27 '13 at 00:58
  • 1
    This is the way I usually do it, I would add that you should make a enum for the tags and compare that to the buttons tag – Yuliani Noriega May 27 '13 at 01:21
  • 3
    Instead of casting the `id` parameter `sender`, you could declare your method as: `- (void)buttonClicked:(UIButton *)button {`. – rmaddy May 27 '13 at 01:43
  • Hi rmaddy, I liked your approach. The problem here was I totally forgot about the type casting, it did not come into my mind. All, suggestions look great, thank you all. – jeewan May 27 '13 at 01:52
1

Store the button in a property on your view controller and then check against that property:

@property (nonatomic, weak) UIButton *buttonOne;

- (void)buttonTapped:(id)sender {
    if (sender == buttonOne) {
        // button one was tapped
    }
}

or simply assign different selectors to each button.

[buttonOne addTarget:self
            action:@selector(buttonOneTapped:)
 forControlEvents:UIControlEventTouchUp];
[buttonTwo addTarget:self
            action:@selector(buttonTwoTapped:)
 forControlEvents:UIControlEventTouchUp];
Stepan Hruda
  • 596
  • 5
  • 12