繁体   English   中英

iPhone-按住时捕获UIButton事件

[英]iPhone - catch UIButton events when kept pressed

我想每隔0.2秒捕获一次UIButton按下的事件。 我的意思是,我想使专用于按钮的IBAction在按住UIButton时每0.2秒触发一次。 我已经尝试了一些在网上找到的代码,并且我知道我需要使用计时器。 但是这样做,我在catch方法中失去了我需要的“ sender”属性。

我如何才能做到这一点?

创建NSTimer ,可以将自定义对象作为userInfo字段附加到该对象(例如,检查文档中的+scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:方法-userInfo参数)。

因此,您可以使用userInfo字段传递发件人。

您不必使用计时器,可以实现:

  • (void)touchesBegan:(NSSet *)touch withEvent:(UIEvent *)event;
  • (void)touchesEnded:(NSSet *)与事件接触:(UIEvent *)事件;

按钮的事件。

如果期望按秒顺序按下按钮,则可以执行以下操作:

#import <Foundation/Foundation.h>

@interface FancyButton: UIButton
{

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event ;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
@end



#import "FancyButton.h"

NSTimeInterval buttonPressedTime;

@implementation FancyButton
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{  
    buttonPressedTime = [event timestamp];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{  
    if([event timestamp] - buttonPressedTime) > your_desired_press_time)
    {
        [self your_fancy_message]; // or any other processing you will do
    }
   buttonPressedTime = 0;
}
@end

希望对您有所帮助。

如果您的计时器设置正确并且可以正常工作,那么您所需要的只是对所按下按钮的某种引用。 您可以在类中创建一个iVar以及一个属性,然后在touchDownInside事件处理程序中对其进行设置。 然后在计时器方法中进行检查。

如果看到一些代码,我可能会提供更好的建议,但是当您安排触发选择器时,您可以指定目标对象。 只要对象可以访问您的发件人,您就很好。

在您的情况下(如果我正确理解),我将使用发送方更新目标对象:按下UIButton时,使用UIButton更新目标对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM