0

我已经查看并找到了使用按钮制作 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);
}];
}
4

2 回答 2

1

您可以使用UIControlEventTouchDowncontrol 事件来启动方法运行,UIControlEventTouchUpInside或者使用类似的方法来检测按钮何时不再被“按下”。

设置按钮的操作,例如:

[myButton addTarget:self action:@selector(startButtonTouch:) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(endButtonTouch:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];

(注意上面会导致按钮内外的touch up调用endButtonTouch:方法。)

然后添加 startButtonTouch: 和 endButtonTouch 方法,例如:

- (void)startButtonTouch:(id)sender {
    // start the process running...
}

- (void)endButtonTouch:(id)sender {
// stop the running process...
}

如果您想在用户拖动按钮时结束它,请添加UIControlEventTouchDragExit

于 2014-10-21T04:49:31.300 回答
0

设置按钮向上向下状态:

- (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];
于 2014-10-21T04:51:52.793 回答