0

我有 2 个按钮,我按住它们,它们在屏幕上向左或向右移动图像,我希望他的图像停在屏幕边缘,但不能再移动,我不知道如何添加代码来做到这一点。

    -(IBAction)Left:(id)sender{
    [MenuClick play];
    LeftTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(GoLeft) userInfo:nil repeats:YES];
    if (Left == nil) {
        LeftTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(GoLeft) userInfo:nil repeats:YES];
    }
}

-(IBAction)StopLeft:(id)sender{
    [LeftTimer invalidate];
    LeftTimer = nil;
}

-(IBAction)Right:(id)sender{
    [MenuClick play];
    RightTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(GoRight) userInfo:nil repeats:YES];
    if (Right == nil) {
        RightTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(GoRight) userInfo:nil repeats:YES];
    }
}

-(IBAction)StopRight:(id)sender{
    [RightTimer invalidate];
    RightTimer = nil;
}

-(void)GoLeft{
    Ship.center = CGPointMake(Ship.center.x -5, Ship.center.y);
}

-(void)GoRight{
    Ship.center = CGPointMake(Ship.center.x +5, Ship.center.y);
}
4

2 回答 2

1

更新GoLeftGoRight方法以检查图像相对于视图边界的位置。

假设self是一个UIViewController代表屏幕...

-(void)GoRight{
    CGPoint proposedOrigin = CGPointMake(Ship.center.x +5, Ship.center.y);
    CGRect screenFrame = self.view.frame;

    // The ship's origin + width gets the right-most point,
    // compare this against the main view's width to determine
    // whether or not it should be moved.
    if (proposedOrigin.x + Ship.frame.size.width/2.0 < screenFrame.size.width) {
        Ship.center = proposedOrigin;
    } else {
        [self StopRight:nil];
    }
}

我会留给你找出(更简单的)GoLeft修改。

于 2013-09-10T18:33:28.127 回答
0

在评论的基础上编辑

- (void)moveLeft
{
    CGPoint newCenter = ship.center;

    if (CGRectGetMinX(ship.frame)-5 <= 0)
    {
        newCenter.x=ship.bounds.size.width/2.0;
        [self stopLeft:nil];
    }
    else
    {
       center.x-=5;
    }
    ship.center = newCenter;
}


- (void)moveRight
{
    CGPoint newCenter = ship.center;

    if (CGRectGetMaxX(ship.frame)+5 >= self.view.bounds.width)
    {
        newCenter.x=self.view.bounds.width-ship.bounds.size.width/2.0;
        [self stopRight:nil];
    }
    else
    {
       center.x+=5;
    }
    ship.center = newCenter;
}
于 2013-09-10T18:35:30.153 回答