限制超视图边界内子视图的移动

时间:2017-11-21 13:03:32

标签: ios objective-c cocoa-touch uiview

我有一个UIView,这是我的VC视图(self.view),我在其中添加了另一个UIView作为子视图,看起来像一个正方形。我想限制superview里面的子视图的移动。基本上,子视图不应超出超视范围。
我确实实现了

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
// i check if point of touch is inside my superview i set the center i.e
UITouch *touch = [[UITouch allObjects] firstObject];
if (CGRectContainsPoint(subview.frame, [touch locationInView:self.view])) {
// set the center here... i.e
subview.center = [touch locationInView:self.view];
}

这项工作和子视图正在移动,但它也移动到超视图之外;我怎样才能限制超视图中的移动?

我甚至尝过类似的东西。

if (CGRectContainsRect(self.view.bounds, subview.frame)) {
// this condition works but i don't know why my subview sticks to the sides of superview if i try to drag it through the bounds of superview
}

我在touchesBegan,touchesCancelled中没有做任何事情,也没有任何与touchesEnd相关的内容。

1 个答案:

答案 0 :(得分:3)

您需要检查要移动的视图的“新框架”,并将其边缘与其超视图的边界进行比较:

@implementation DraggableView

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // restrict to superview bounds
    CGRect parentFrame = [self.superview bounds];

    UITouch *aTouch = [touches anyObject];
    CGPoint location = [aTouch locationInView:self];
    CGPoint previousLocation = [aTouch previousLocationInView:self];

    // new frame for this "draggable" subview, based on touch offset when moving
    CGRect newFrame = CGRectOffset(self.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));

    if (newFrame.origin.x < 0) {

        // if the new left edge would be outside the superview (dragging left),
        // set the new origin.x to Zero
        newFrame.origin.x = 0;

    } else if (newFrame.origin.x + newFrame.size.width > parentFrame.size.width) {

        // if the right edge would be outside the superview (dragging right),
        // set the new origin.x to the width of the superview - the width of this view
        newFrame.origin.x = parentFrame.size.width - self.frame.size.width;

    }

    if (newFrame.origin.y < 0) {

        // if the new top edge would be outside the superview (dragging up),
        // set the new origin.y to Zero
        newFrame.origin.y = 0;

    } else if (newFrame.origin.y + newFrame.size.height > parentFrame.size.height) {

        // if the new bottom edge would be outside the superview (dragging down),
        // set the new origin.y to the height of the superview - the height of this view
        newFrame.origin.y = parentFrame.size.height - self.frame.size.height;

    }

    // update this view's frame
    self.frame = newFrame;
}

@end

这也使用了触摸的偏移,而不是将视图置于触摸的中心(因此当你开始拖动时它不会“跳到你的手指上”)。

编辑以澄清:在此图片中,蓝色视图类为DraggableView ...无法将其拖动到其superView(红色视图)之外。

enter image description here

相关问题