我看过并找到了制作带按钮的d-pad的代码,但你必须不断点击按钮才能使其工作。所以,如果你想上去,你必须不断地向上按压。如何在用户按下按钮的情况下使对象移动。这是我已经的按钮代码
-(IBAction)moveLeft:(id)sender{
Robot.center = CGPointMake(Robot.center.x-10, Robot.center.y);
[UIView animateWithDuration:0.5 animations:^{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y+10);
}];
}
-(IBAction)moveRight:(id)sender{
Robot.center = CGPointMake(Robot.center.x+10, Robot.center.y);
[UIView animateWithDuration:0.5 animations:^{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y+10);
}];
}
-(IBAction)moveUp:(id)sender{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y-10);
[UIView animateWithDuration:0.5 animations:^{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y+10);
}];
}
-(IBAction)moveDown:(id)sender{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y+10);
[UIView animateWithDuration:0.5 animations:^{
Robot.center = CGPointMake(Robot.center.x, Robot.center.y+10);
}];
}
您可以使用UIControlEventTouchDown
控制事件来启动方法运行,使用UIControlEventTouchUpInside
或类似事件来检测按钮何时不再"按下"。
设置按钮的操作,例如:
[myButton addTarget:self action:@selector(startButtonTouch:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(endButtonTouch:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
(请注意,以上内容将导致按钮内外的触摸,以调用endButtonTouch:方法。)
然后添加startButtonTouch:和endButtonTouch方法,例如:
- (void)startButtonTouch:(id)sender {
// start the process running...
}
- (void)endButtonTouch:(id)sender {
// stop the running process...
}
如果您想在用户拖动到按钮外部时结束它,也可以添加UIControlEventTouchDragExit
。
设置按钮上下状态:
- (IBAction)touchUpIn_btnUp:(id)sender {
self.buttonUpIsDown = NO;
}
- (IBAction)touchDownIn_btnUp:(id)sender {
self.buttonUpIsDown = YES;
}
- (IBAction)touchUpIn_btnLeft:(id)sender {
self.buttonLeftIsDown = NO;
}
- (IBAction)touchDownIn_btnLeft:(id)sender {
self.buttonLeftIsDown = YES;
}
- (IBAction)touchUpIn_btnRight:(id)sender {
self.buttonRightIsDown = NO;
}
- (IBAction)touchDownIn_btnRight:(id)sender {
self.buttonRightIsDown = YES;
}
- (IBAction)touchUpIn_btnDown:(id)sender {
self.buttonDownIsDown = NO;
}
- (IBAction)touchDownIn_btnDown:(id)sender {
self.buttonDownIsDown = YES;
}
检查循环中的状态
- (void) updateControls {
if (self.buttonUpIsDown) {
// move up
}
if (self.buttonDownIsDown) {
// move down
}
if (self.buttonLeftIsDown) {
// move left
}
if (self.buttonRightIsDown) {
// move right
}
}
调用循环:
[NSTimer scheduledTimerWithTimeInterval:MAIN_LOOP_TIME target:self selector:@selector(updateControls) userInfo:nil repeats:YES];