我有四种简单的方法、四个按钮和一个对象。
- (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);
}
当我按下按钮时,该方法会执行一次。当连续按下按钮时,效果是一样的。 我必须做什么才能当我连续按下按钮时我的物体继续向左移动?
最佳答案
正如 @Maudicus 所说,您可能需要对 NSTimer 进行一些操作才能连续按下按钮触发。我要使用的示例是在屏幕上移动一个对象(因为无论如何您都想这样做)。我使用了分级移动,因为我不知道您是否正在编写基于网格的游戏,因此需要恰好 5 个像素的移动。只需删除所有的 stepSize 代码并将其设置为 5(如果您这样做的话)。
编写一个计时器回调函数,检查是否设置了
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]; }
在当前类中创建计时器属性
.h
:@property (nonatomic, retain) NSTimer *moveTimer;
在您的
.m
中综合它:@synthesize moveTimer;
按下按钮时创建计时器对象。在
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];
当按钮被释放时(再次使用上述方法之一,
touchesEnded:withEvent:
用于 Touch Up Inside 甚至可能是 Touch Up Outside,或另一个IBAction
在这两个事件上),从外部使计时器无效:[self.moveTimer invalidate]; self.moveTimer = nil;
关于objective-c - obj-c中连续按下按钮时如何重复执行某个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8248768/