在按住的情况下使 UIButton 连续触发的方法?

Way to make a UIButton continuously fire during a press-and-hold situation?(在按住的情况下使 UIButton 连续触发的方法?)

本文介绍了在按住的情况下使 UIButton 连续触发的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道当你按住方向键上的右键时马里奥是如何一直向右跑的吗?以同样的方式,我希望我的 UIButton 在它被按住的时间内持续触发它的动作.这对 UIButton 可行吗?如果不是,这是否可以通过以某种方式覆盖触摸处理方法来处理 UIImageView ?实际上,在尝试使用 UIButton 完成此操作之前,我有一些 UIImageViews(被安排用作 D-Pad),它们通过触摸处理方法进行检查,但事情开始变得混乱,所以我认为这可以通过 UIButton 更轻松地完成,因此切换了.任何知道如何识别连续、静止(不移动)的向下触摸的人,请分享.

You know how Mario just keeps running to the right when you press and hold the right-button on the D-Pad? In the same manner, I want my UIButton to continuously fire its action for the duration that it is held down. Is this possible for a UIButton? If not, is this possible to do with a UIImageView by overriding a touch handling method in a certain way? Actually, before trying to do get this done with UIButton I had some UIImageViews (Arranged to function as a D-Pad) that were checked by touch handling methods but things started to get messy so I thought this could be done easier with UIButton and thus switched over. Anybody who knows how to get recognition of a continuous, stationary (not-moved) down-touch, please share.

推荐答案

不要使用按钮,使用多点触控和 NSTimer:

Don't use a button, use multi-touch and NSTimer:

在你的界面中创建一个本地视图 NSTimer 对象,然后使用它来启动/取消计时器

Make a view-local NSTimer object inside your interface, then use it to start/cancel the timer

-(void)movePlayer:(id)sender {
   <Code to move player>
}

-(void)touchesBegan:(NSSet*)touches  withEvent:(UIEvent*)event {
    timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(movePlayer:) userInfo:nil repeats:YES];
}

-(void)touchesEnded:(NSSet*)touches  withEvent:(UIEvent*)event {
   if (timer != nil) 
      [timer invalidate];
      timer = nil;
}

-(void)touchesMoved:(NSSet*)touches  withEvent:(UIEvent*)event {
    if (timer != nil) {
       [timer invalidate];
       timer = nil;
    }
}

这样,您可以以预定义的时间间隔重复事件,而不必依赖按钮,并获得您正在寻找的重复行为.注意 touchesMoved 触发器 - 如果他们移动手指,这会取消计时器,并且玩家停止移动.

This way, you can repeat the event at a predefined interval, and not have to rely on a button, and get the repeat behaviour you're looking for. Note the touchesMoved trigger - if they move their finger, this cancels the timer, and the player stops moving.

这篇关于在按住的情况下使 UIButton 连续触发的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在按住的情况下使 UIButton 连续触发的方法?

基础教程推荐