为UIPangesture添加边界

时间:2016-04-08 08:09:37

标签: ios objective-c subview uipangesturerecognizer

我在UILabel中有一个subviewpanGesture上有一个pinchGestureUILabel。截至目前,我可以移动UILabel横过所有视图。我希望此UILabel留在subView区域内。我怎么做到这一点?

- (void)handlePanGesture:(UIPanGestureRecognizer *)panGesture {
CGPoint translation = [panGesture translationInView:panGesture.view.superview];

if (UIGestureRecognizerStateBegan == panGesture.state ||UIGestureRecognizerStateChanged == panGesture.state) {
    panGesture.view.center = CGPointMake(panGesture.view.center.x + translation.x,
                                         panGesture.view.center.y + translation.y);
    [panGesture setTranslation:CGPointZero inView:self.view];
 }
}

在这一行中,

CGPoint translation = [panGesture translationInView:panGesture.view.superview];

它将它设置为superView,我正在尝试将其设置为我的subView,但我似乎无法弄明白。

1 个答案:

答案 0 :(得分:1)

这是我的代码,用于处理可拖动按钮并将其限制在主视图边界 我希望这段代码可以帮到你

 CGPoint translation = [recognizer translationInView:self.view];
    CGRect recognizerFrame = recognizer.view.frame;
    recognizerFrame.origin.x += translation.x;
    recognizerFrame.origin.y += translation.y;

    // Check if UIImageView is completely inside its superView
    if (CGRectContainsRect(self.view.bounds, recognizerFrame)) {
        recognizer.view.frame = recognizerFrame;
    }
    // Else check if UIImageView is vertically and/or horizontally outside of its
    // superView. If yes, then set UImageView's frame accordingly.
    // This is required so that when user pans rapidly then it provides smooth translation.
    else {
        // Check vertically
        if (recognizerFrame.origin.y < self.view.bounds.origin.y) {
            recognizerFrame.origin.y = 0;
        }
        else if (recognizerFrame.origin.y + recognizerFrame.size.height > self.view.bounds.size.height) {
            recognizerFrame.origin.y = self.view.bounds.size.height - recognizerFrame.size.height;
        }

        // Check horizantally
        if (recognizerFrame.origin.x < self.view.bounds.origin.x) {
            recognizerFrame.origin.x = 0;
        }
        else if (recognizerFrame.origin.x + recognizerFrame.size.width > self.view.bounds.size.width) {
            recognizerFrame.origin.x = self.view.bounds.size.width - recognizerFrame.size.width;
        }
    }

    // Reset translation so that on next pan recognition
    // we get correct translation value
    [recognizer setTranslation:CGPointZero inView:self.view];