【问题标题】:Add boundaries to a UIPangesture向 UIPangesture 添加边界
【发布时间】:2016-04-08 08:09:37
【问题描述】:

我在subview 中有一个UILabel,在UILabel 上有一个panGesturepinchGesture。截至目前,我可以将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,但我似乎无法弄清楚。

【问题讨论】:

    标签: ios objective-c subview uipangesturerecognizer


    【解决方案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];
    

    【讨论】:

    • 感谢您的帮助。您愿意帮助我了解如何将其实现到我自己的代码中吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多