0

我需要在屏幕上拖动一个对象,问题是当我拖动这个对象时,它可能会被拖出 iPhone/iPad 的屏幕,我怎样才能避免这种情况,这是我的代码:

  float startingX;
    float startingY;


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    UITouch *touch = [touches anyObject];
    startingX = [touch locationInView:self.view].x;
    startingY = [touch locationInView:self.view].y;
}




- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{


    CGPoint currentPoint = objectView.frame.origin;
    float xForView, yForView;
    UITouch *touch = [touches anyObject];
    float newX = [touch locationInView:self.view].x;
    float deltaX;
    if(startingX > newX){
        deltaX = startingX - newX;
        xForView = currentPoint.x - deltaX;
    } else if(newX > startingX){
        deltaX = newX - startingX;
        xForView = currentPoint.x + deltaX;
    } else xForView = currentPoint.x;

    float newY = [touch locationInView:self.view].y;
    float deltaY;
    if(startingY > newY){
        deltaY = startingY - newY;
        yForView = currentPoint.y - deltaY;
    } else if(newY > startingY){
        deltaY = newY - startingY;
        yForView = currentPoint.y + deltaY;
    } else yForView = currentPoint.y;

    CGRect newFrame = CGRectMake(xForView, yForView, objectView.frame.size.width, objectView.frame.size.height);
    objectView.frame = newFrame;

    startingX = newX;
    startingY = newY;
}
4

2 回答 2

0

视图属性的原点frame位于其父视图的坐标系中。center如果您只想移动它,您也可以设置视图的属性(它也在它的超级视图的坐标系中)。这是执行此操作的算法:在touchesBegan:方法中,您获取坐标并根据视图的中心计算偏移量,然后在 touchesMoved 中,您只需设置视图的中心,同时考虑偏移量。

于 2012-04-23T07:44:14.683 回答
0

您可以在 touchmove 函数中添加一个处理程序,例如:

    if(currentPoint.x < 0) //which means it already moved out of your window 
{   
[yourObject setFrame:CGRectMake(0, currentPoint.y, yourObject.frame.size.width, yourObject.frame.size.height)];
} 
if(currentPoint.y < 0) //preventing your object goes upward beyond window 
{   
[yourObject setFrame:CGRectMake(currentPoint.x, 0, yourObject.frame.size.width, yourObject.frame.size.height)];
}

并且使用 if(currentPoint.y > self.view.frame.size.width) 和高度也这样做,这样对象就不会在下侧和右侧超出您的窗口

祝你好运

于 2012-04-23T09:21:48.600 回答