如何为图像添加坐标限制

时间:2013-09-10 18:14:30

标签: objective-c

我有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);
}

2 个答案:

答案 0 :(得分: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修改。

答案 1 :(得分: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;
}