2012-04-23 75 views
0

我需要拖动屏幕上的对象,问题是,当我拖着这个对象也可能被拖出iPhone/iPad的屏幕,我怎么能避免此这种情况我的代码:iOS版:问题与拖动对象

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; 
} 

回答

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)]; 
} 

和这样做也有,如果(currentPoint.y> self.view.frame.size.width)和高度,从而使对象不会超越你的窗口下侧和右侧

好运

+0

谢谢哪儿我应该把这个代码,谢谢 – 2012-04-23 10:26:38

+0

抱歉长的答案,你应该把它放在你的touchesMoved方法,以便处理程序将始终检查对象超出范围的,当你拖动 – 2012-04-24 08:52:05

+0

是的,我知道我的意思是其中touchesMoved到底是什么?因为我把这个线,什么也没有发生 – 2012-04-24 09:13:04

0

视图的frame财产的起源是在它的父坐标系统。如果你只想移动它,你也可以设置你的视图的center属性(它也在它的超视图坐标系中)。这里是algoritm做到这一点:在touchesBegan:方法你得到的坐标并计算根据视图的中心偏移,则在touchesMoved您只需设置采取心目中的视图中心的偏移量。