如何判断某个按钮是否在特定时间被按下

How to tell if a button is pressed at a certain time

我有一个带图像的按钮,过一会儿按钮图像会改变,几秒钟后又变回来。我希望能够判断在图像不同时是否单击了按钮。谢谢!

您有多种选择,但我将详细介绍其中两种。第一个更加独立和万无一失,但第二个可以说更容易阅读和理解。

检查背景图片

执行此操作的最简单方法可能是仅针对图像本身进行测试。图像会不时发生变化,但您并不真正关心何时 按钮被按下,您只关心哪个背景在按下时可见。

换句话说,你真正需要知道的是按钮的背景是MainBackground还是AlternateBackground,所以当按钮被按下时,你可以简单地检查它是哪一个。

尝试这样的操作,因为按下按钮时:

-(void)buttonPressed:(UIButton*)sender {
    UIImage *mainBackground = [UIImage imageNamed:@"YOUR_IMAGE_NAME"];

    NSData *imgdata1 = UIImagePNGRepresentation(sender.image);
    NSData *imgdata2 = UIImagePNGRepresentation(mainBackground);

    if ([imgdata1 isEqualToData:imgdata2]) {
        // The button's background is the MainBackground, do one thing
    } else {
        // The button's background is the AlternateBackground, do another thing
    }
}

跟踪当前显示的图像

或者,您可以在图像背景更改时翻转 BOOL 值。像...

@property BOOL isMainBackground;

...在您的 H 文件中,然后每当您设置按钮的背景图像时,您还设置了 self.isMainBackground = YES;self.isMainBackground = NO;

然后,您的按钮按下方法将如下所示:

-(void)buttonPressed:(UIButton*)sender {
    if (self.isMainBackground) {
        // The button's background is the MainBackground, do one thing
    } else {
        // The button's background is the AlternateBackground, do another thing
    }
}