iOS:拖动对象的问题

时间:2012-04-23 07:28:06

标签: iphone objective-c ios xcode ipad

我需要在屏幕上拖动一个对象,问题是当我拖动这个对象时它可能会被拖出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;
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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&gt; self.view.frame.size.width)和高度这样做,这样对象就不会超出你的窗口的下方和右侧

祝你好运