UIPanGestureRecognizer 限制坐标 [英] UIPanGestureRecognizer limit to coordinates

查看:49
本文介绍了UIPanGestureRecognizer 限制坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主 UIView 中添加了一个子视图(称为 panel),并向其添加了gestureRecognizer,因为我希望它仅可拖动 Y 轴且仅适用于某些限制(即 160、300, 超过 300 就不行了).

I added to my main UIView a subview (called panel) and i added gestureRecognizer to it because i want it to be draggable only for the Y axis and only for certain limits (i.e. 160, 300, over 300 it can't go).

我以这种方式实现了手势处理

I implemented the gesture handling that way

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:self.view]; 
    recognizer.view.center = CGPointMake(self.view.frame.size.width/2, recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view.superview];

    //now limit the drag to some coordinates
   if (y == 300 || y == 190){
       no more drag
    }
}

但现在我不知道如何将阻力限制在这些坐标上.

but now i don't know how to limit the drag to those coordinates.

这不是一个巨大的视图,它只是一个包含工具栏和按钮的小视图.

It's not a huge view, it's just a small view containing a toolbar and a button.

如何将拖动限制为坐标?(x = 160(中间屏幕), y =404 ) <- 示例

How can i limit the drag to a coordinate? (x = 160(middle screen), y =404 ) <- example

中心应该是什么?

我用谷歌搜索了很多,但没有找到具体的答案.

I googled a lot but i didn't find a concrete answer.

提前致谢

推荐答案

首先,您需要在更改视图中心之前强制执行限制.在检查新中心是否越界之前,您的代码会更改视图的中心.

First, you need to enforce the limit before you change the view's center. Your code changes the view's center before checking if the new center is out of bounds.

其次,您需要使用正确的 C 运算符来测试 Y 坐标.= 运算符是赋值.== 运算符测试相等性,但您也不想使用它.

Second, you need to use the correct C operators for testing the Y coordinate. The = operator is assignment. The == operator tests for equality, but you don't want to use that either.

第三,如果新中心越界,您可能不想重置识别器的翻译.当拖动越界时重置平移将使用户的手指与其拖动的视图断开连接.

Third, you probably don't want to reset the recognizer's translation if the new center is out-of-bounds. Resetting the translation when the drag goes out of bounds will disconnect the user's finger from the view he's dragging.

你可能想要这样的东西:

You probably want something like this:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:self.view];

    // Figure out where the user is trying to drag the view.
    CGPoint newCenter = CGPointMake(self.view.bounds.size.width / 2,
        recognizer.view.center.y + translation.y);

    // See if the new position is in bounds.
    if (newCenter.y >= 160 && newCenter.y <= 300) {
        recognizer.view.center = newCenter;
        [recognizer setTranslation:CGPointZero inView:self.view];
    }
}

这篇关于UIPanGestureRecognizer 限制坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆