检测按下了哪个按钮? (然后行动)

Posted

技术标签:

【中文标题】检测按下了哪个按钮? (然后行动)【英文标题】:Detect which button is pressed? (then action) 【发布时间】:2010-10-14 14:54:30 【问题描述】:

这是我在 SOF 上的第一篇文章。 我是objective-c的新程序员。 这是我正在处理的“问题”

我创建了 2 个 UIbutton :一个用于从屏幕顶部拉出 UIImageView,另一个用于将其推回。 我有动作的代码** 但我不知道如何将它与 if 语句关联起来

-(void)viewDidLoad
super viewDidLoad]

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 button1.frame = CGRectMake(200, 0, 90, 30);
[button1 addTarget:self action:@selector(buttonPressed1) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:button1];

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 button2.frame = CGRectMake(400, 0, 90, 30);
[button2 addTarget:self action:@selector(buttonPressed2) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:button2];



**

-(void)buttonPressed1 

 double speed = 1 / round(random() % 100) + 1.0;

 UIImageView *banetteView2 = [[UIImageView alloc] initWithImage:banetteImage];
 banetteView2.frame = CGRectMake(100, -740, 568, 790);
 banetteView2.opaque = NO;
 [self.view addSubview:banetteView2];

 [UIView beginAnimations:nil context:banetteView2];
 [UIView setAnimationDuration: 2*speed ];

 //banetteView2.frame = CGRectMake(100, -1, 568, 790);

 UIImageView *banetteView = [[UIImageView alloc] initWithImage:banetteImage];
 banetteView.frame = CGRectMake(100, -740, 568, 790);
 banetteView.opaque = NO;
 banetteView.hidden = YES;
 [self.view addSubview:banetteView];


 [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
 [UIView setAnimationDelegate:self];
 [UIView commitAnimations];




- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 

 UIImageView *banetteView2 = context;
 [banetteView2 release];


 double speed = 1 / round(random() % 100) + 1.0;
 banetteView2.frame = CGRectMake(100, 0, 568, 790);
 banetteView2.opaque = NO;
 [self.view addSubview:banetteView2];

 [UIView beginAnimations:nil context:banetteView2];
 [UIView setAnimationDuration: 2*speed ];

 //banetteView2.frame = CGRectMake(100, -740, 568, 790);


【问题讨论】:

【参考方案1】:

我不确定这是否适用于 UIButtons,但对于常规的 Cocoa 按钮,您可以像这样为发件人添加一个参数:

-(void)buttonPressed1:(id)sender

    // And now you can check which button is the sender
    if(sender==button1)
        // Do stuff....

当然,当您设置按钮操作时,您需要在选择器上添加一个冒号:@selector(buttonPressed1:)

【讨论】:

我认为这应该可行,但事实是我的 button1 是“未声明的”。我尝试在 buttonPressed1 函数中重新创建它,但也没有用。 这是因为它被限制在声明它的方法的范围内。为了从多个方法访问它,您需要在类范围内声明它。您可以通过在类的接口、.h 文件中声明它来做到这一点,或者如果它不需要在接口中可见,您可以在方法之外的类中声明它,在 @implementation 和例如第一种方法。 我通过改编这段代码找到mobile.tutsplus.com/tutorials/iphone/…【参考方案2】:

我通过改编这段代码找到的

http://mobile.tutsplus.com/tutorials/iphone/iphone-sdk-learning-about-touch-events-basic-game-animation/

【讨论】:

以上是关于检测按下了哪个按钮? (然后行动)的主要内容,如果未能解决你的问题,请参考以下文章

如何检测哪个操纵杆按下了按钮?

如何检测在 PyQt5 中按下了动态添加的按钮之一? [复制]

RadGridView 检测 CellClick 事件按钮

iOS如何识别按下了哪个图像(按钮)?

检测在 SwiftUI 中点击的系统警报按钮

用户按下了 UIAlertView 上的哪个按钮?