UIButton:多个按钮 - 如何检测事件并找到被点击的按钮“

时间:2013-05-27 00:51:12

标签: objective-c uibutton programmatically-created

如何检测已点击的UIButton:

-(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

}

2 个答案:

答案 0 :(得分:2)

将您的发件人投放到UIButton并比较标记值。

UIButton *button = (UIButton *)sender;

if (button.tag == 1) {

} else {

}

答案 1 :(得分:1)

将按钮存储在视图控制器的属性中,然后检查该属性:

@property (nonatomic, weak) UIButton *buttonOne;

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

或简单地为每个按钮指定不同的选择器。

[buttonOne addTarget:self
            action:@selector(buttonOneTapped:)
 forControlEvents:UIControlEventTouchUp];
[buttonTwo addTarget:self
            action:@selector(buttonTwoTapped:)
 forControlEvents:UIControlEventTouchUp];