防止视图被拖出屏幕

时间:2014-02-26 22:18:48

标签: ios objective-c

我需要阻止视图被拖过屏幕边缘。换句话说,当视图边缘到达屏幕边缘时,视图无法在该方向上进一步移动。

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

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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
//...

答案 2 :(得分:0)

您是否尝试过CGRectContainsRect?这是文档:https://developer.apple.com/library/ios/documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsRect

if ( CGRectContainsRect(superViewBounds,subViewBounds) ){
//within the screen bounds
} else {
//_not_ within the screen bounds
}