在obj-c中连续按下button时如何重复执行动作

我有四个简单的方法,四个button和一个对象。

- (IBAction)left:(id)sender{ object.center = CGPointMake(object.center.x - 5, object.center.y); } - (IBAction)right:(id)sender{ object.center = CGPointMake(object.center.x + 5, object.center.y); } - (IBAction)down:(id)sender{ object.center = CGPointMake(object.center.x, object.center.y + 5); } - (IBAction)up:(id)sender{ object.center = CGPointMake(object.center.x, object.center.y - 5); } 

当我按下button时,该方法被执行一次。 当button连续按下时,它是一样的。 我需要做什么,当我连续按下button时,我的对象继续向左移动?

正如@Maudicus所说的,你可能需要用NSTimer来做一些事情来获得连续的button触发。 我要使用的例子是在屏幕上移动一个对象(因为无论如何你都要这样做)。 我使用渐变移动,因为我不知道你是否正在编写一个基于网格的游戏,所以需要5个像素的运动。 只要删除所有的stepSize代码,并将其设置为5,如果这是你所做的。

  1. 编写一个定时器callback函数,它检查一个BOOL是否被设置,如果这样继续触发自己:

     - (void)moveObjectLeft:(NSTimer *)timer { // check the total move offset and/or the X location of the object here // if the object can't be moved further left then invalidate the timer // you don't need to check whether the button is still being pressed //[timer invalidate]; //return; // the object moves gradually faster as you hold the button down for longer NSNumber *moveOffset = (NSNumber *)[timer userInfo]; NSUInteger stepSize = 1; if(moveOffset >= 40) stepSize = 10; else if(moveOffset >= 15) stepSize = 5; else if(moveOffset >= 5) stepSize = 2; // move the object object.center = CGPointMake(object.center.x - stepSize, object.center.y); // store the new total move offset for this press moveOffset += stepSize; [timer setUserInfo:moveOffset]; } 
  2. 在当前类中创build一个timer属性.h

     @property (nonatomic, retain) NSTimer *moveTimer; 
  3. .m合成它:

     @synthesize moveTimer; 
  4. 按下button时创build您的计时器对象。 在touchesBegan:withEvent:执行此操作,并检查它是否是Touch Down事件,或者将Interface Builder中的Touch Down事件连接到IBAction方法。

     NSNumber *moveOffset = [NSNumber numberWithUnsignedInt:0]; self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(moveObject:) userInfo:moveOffset repeats:YES]; 
  5. 当释放button时(再次使用上述方法之一, touchesEnded:withEvent:对于Touch Up Inside或者甚至是Touch touchesEnded:withEvent: Outside或者对这两个事件的另一个IBAction ),从外部使定时器无效:

     [self.moveTimer invalidate]; self.moveTimer = nil; 

当一个button发出mousedown事件时,开始移动。 当button发出mouseup事件时,停止移动。

小心; 如果可以同时按下多个button,这可能会很有趣。

我认为你需要安排一个计时器,并重复检查button状态的方法。

//假设定时器设置为testingbutton状态,每x秒触发一次controlLoop

 -(void)controlsLoop { if (leftButton.state == UIControlStateSelected || leftButton.state == UIControlStateHighlighted) { } } 

我从来没有这样做过,所以玩得开心。 我通常在Cocos2d中实现你想要的控制,

实施这些方法可能会更好

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event 

设置你想移动物体的方向,还有一个触发实际移动的定时器。