当对象移动到某个帧时如何停止 UIPanGestureRecognizer

Posted

技术标签:

【中文标题】当对象移动到某个帧时如何停止 UIPanGestureRecognizer【英文标题】:How to stop UIPanGestureRecognizer when object moved to certain frame 【发布时间】:2011-11-10 11:25:55 【问题描述】:

我有一个图像类型的对象,我正在使用 UIPanGestureRecognizer 移动它,当对象到达某个帧时,我需要停止识别 UIPanGestureRecognizer。

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
    [panRecognizer setMinimumNumberOfTouches:1];
    [panRecognizer setMaximumNumberOfTouches:1];
    [panRecognizer setDelegate:self];
    [templatePhotoPlaceholderView addGestureRecognizer:panRecognizer];

-(void)move:(UIPanGestureRecognizer *)gestureRecognizer

    CGPoint translatedPoint = [gestureRecognizer translationInView:templatePhotoPlaceholderView];

    if([gestureRecognizer state] == UIGestureRecognizerStateBegan) 
        _firstX = [imageview center].x;
        _firstY = [imageview center].y;
    



    translatedPoint = CGPointMake(_firstX+translatedPoint.x, _firstY+translatedPoint.y);
    //NSLog(@" Move center point :%@", NSStringFromCGPoint(translatedPoint));

    [imageview setCenter:translatedPoint];  


我该怎么做?

【问题讨论】:

【参考方案1】:

UIGestureRecognizers 有一个 enabled 属性。文档:

禁用手势识别器,使其不接收触摸。这 默认值为是。如果您将此属性更改为 NO 而 手势识别器当前正在识别一个手势,该手势 识别器转换到取消状态。

编辑:

只需将 enabled 属性设置为 NO。

gestureRecognizer.enabled = NO;

【讨论】:

你好 jbat。你能给我一些行代码示例吗?用于停止 UIGestureRecognizers【参考方案2】:

当您需要阻止 UIPanGestureRecognizer 识别手势时,只需将此代码行(如 jbat100 所说)放在-(void)move:(UIPanGestureRecognizer *)gestureRecognizer

gestureRecognizer.enabled = NO;

在此行之后,您的gestureRecognizer 状态设置为"UIGestureRecognizerStateCancelled"

然后只需在您的 -(void)move:(UIPanGestureRecognizer *)gestureRecognizer 函数中添加几行:

if ([gestureRecognizer state] == UIGestureRecognizerStateCancelled) 
     gestureRecognizer.enabled = YES;

您将能够使用手势识别器

编辑

这里是sn-p的代码:

- (void)move:(UIPanGestureRecognizer *)gestureRecognizer 
    BOOL cancelPanGesture = YES;
    if (cancelPanGesture) 
        /* 
         After this line gesture recognizer will be disabled, state will be UIGestureRecognizerStateCancelled
         and this method (move:) will fire one more time.
         */
        gestureRecognizer.enabled = NO;
    
    if (gestureRecognizer.state == UIGestureRecognizerStateCancelled) 
        gestureRecognizer.enabled = YES;
    

【讨论】:

答案没有意义,应该在哪里写 gestureRecognizer.enabled = YES;。如果你能详细说明会更有意义。 我喜欢这个。它将识别器的状态封装在该函数中,而不是将愚蠢的shouldCancelPan 实例变量放入您的代码中。 当我到达某个点并设置 recogniser.enabled = false 时使用此技术,它会移动到取消状态,在该状态下我再次启用它,但手势不会开始,直到我抬起手指并重新开始。 【参考方案3】:

设置pangesture.delegate=self,实现委托方法

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer

     //return NO when you reach the frame

【讨论】:

以上是关于当对象移动到某个帧时如何停止 UIPanGestureRecognizer的主要内容,如果未能解决你的问题,请参考以下文章

在帧之间移动时对象更改层?

如何检查刚体是否在移动?

如何停止移动硬盘?

Swift 3 - 当布尔为真时如何移动精灵节点?

当我们移动到另一个视图时如何停止 web 服务调用

如何在使用selenium python切换帧时获得完整的html代码?