Objective c 如何在obj-c中连续按下按钮时重复执行动作
我有四个简单的方法,四个按钮和一个对象Objective c 如何在obj-c中连续按下按钮时重复执行动作,objective-c,ios,cocoa-touch,Objective C,Ios,Cocoa Touch,我有四个简单的方法,四个按钮和一个对象 - (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)sen
- (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);
}
当我按下按钮时,该方法执行一次。当按钮连续按下时,它是相同的。
当我连续按下按钮时,我需要做什么才能使我的对象保持向左移动?当按钮发出其mousedown事件时,开始移动。当按钮发出mouseup事件时,停止移动
小心;如果同时按下多个按钮,这可能会很有趣。我认为您需要安排一个计时器,并重复检查按钮状态的方法 //假设定时器设置为测试按钮状态,每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
要设置要移动对象的方向,并且仍然有一个触发实际移动的计时器。正如@Maudicus所说,您可能需要使用
NSTimer
s来获得连续的按键触发。我将要使用的示例是在屏幕上移动一个对象(因为您无论如何都要这样做)。我使用分级移动是因为我不知道你是否在写一个基于网格的游戏,所以需要5像素的移动。只要删掉所有的步长代码,并将其设置为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;
touchsbegind:withEvent:
中执行此操作并检查它是否为触碰事件,或者将Interface Builder中的触碰事件连接到iAction
方法
NSNumber *moveOffset = [NSNumber numberWithUnsignedInt:0];
self.moveTimer =
[NSTimer
scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(moveObject:)
userInfo:moveOffset
repeats:YES];
touchesend:withEvent:
对于内部或甚至外部的触摸,或者对于这两个事件的另一个iAction
),从外部使计时器失效:
[self.moveTimer invalidate];
self.moveTimer = nil;
但我喜欢为iOS编程。此类事件不存在:/n您在问题中未指定。有接触和释放。使用此选项时,仅当我单击时对象才处于移动状态。当它处于触摸状态时,我必须单击并将光标移动到按钮上,然后对象处于移动状态:/something is error…:/