2014-02-26 115 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座標系。起點是左上角。 –