UIButton:多个按钮 - 如何检测事件并找到点击了哪个按钮”

Posted

技术标签:

【中文标题】UIButton:多个按钮 - 如何检测事件并找到点击了哪个按钮”【英文标题】:UIButton: multiple buttons - how to detect event and find which button was tapped" 【发布时间】:2013-05-27 00:51:11 【问题描述】:

如何检测哪个 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


【问题讨论】:

【参考方案1】:

将您的发件人转换为 UIButton 并比较标签值。

UIButton *button = (UIButton *)sender;

if (button.tag == 1) 

 else 


【讨论】:

一如既往,完全忘记了类型转换:D,谢谢Jean 这是我通常这样做的方式,我要补充一点,您应该为标签创建一个枚举并将其与按钮标签进行比较 您可以将方法声明为:- (void)buttonClicked:(UIButton *)button ,而不是强制转换 id 参数 sender 嗨 rmaddy,我喜欢你的方法。这里的问题是我完全忘记了类型转换,它并没有出现在我的脑海中。所有,建议看起来很棒,谢谢大家。【参考方案2】:

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

@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];

【讨论】:

谢谢 Stepan,我才意识到我是如何忽略了类型转换的 :-)

以上是关于UIButton:多个按钮 - 如何检测事件并找到点击了哪个按钮”的主要内容,如果未能解决你的问题,请参考以下文章

UIButton 不会立即检测到 Touch Down

如何通过让子视图 UIButton 获取新闻事件?

计数按钮事件

如何检测 UIButton 背景图像的变化?

如何检测按钮的保持事件?

检测按下了哪个按钮