2014-02-26 82 views
0

我需要防止视图被拖过屏幕边缘。换句话说,当视图的边缘到达屏幕的边缘时,视图无法在该方向上继续移动。防止视图被拖出屏幕

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touchInfo = [touches anyObject]; 

    if (touchInfo.view == self) 
    { 
     CGPoint touchStart = [touchInfo previousLocationInView:self]; 
     CGPoint touchEnd = [touchInfo locationInView:self]; 
     CGFloat xDifference = touchEnd.x - touchStart.x; 
     CGFloat yDifference = touchEnd.y - touchStart.y; 

     CGPoint newCenter = CGPointMake(self.center.x + xDifference, self.center.y + yDifference); 

     [self setCenter:newCenter]; 
    } 
} 

回答

1
CGRect  bounds = self.bounds; 
CGRect  limit = CGRectInset(self.superview.bounds, bounds.size.width/2., bounds.size.height/2.); 

...

newCenter.x = fmaxf(limit.origin.x, fminf(limit.origin.x + limit.size.width, newCenter.x)); 
newCenter.y = fmaxf(limit.origin.y, fminf(limit.origin.y + limit.size.height, newCenter.y)); 
0

加边检查,这样

CGRect superBounds = self.superView.bounds; 

//check if this is past the right edge 
if (newCenter.x + self.bounds.size.width/2 > superBounds.origin.x) 
{ 
    newCenter.x = superBounds.size.width - self.bounds.size.width/2; 
} 

//Do the same thing for the top, bottom, and left edges 
//... 
+0

如何检查顶部,底部和左边? – jipot

+0

如果您不确定如何检查每个边,您可能需要阅读UIKit坐标系。起点是左上角。 –