是否有可能将UIPanGestureRecognizer子类化,以便在达到某个距离阈值后使其开始状态

时间:2018-06-08 01:46:18

标签: ios objective-c uigesturerecognizer uipangesturerecognizer

我想继承UIPanGestureRecognizer,以便在我的子类中,只有在平移过程中达到一定的距离阈值后,状态才会变为UIGestureRecognizerStateBegan。这意味着经过一定程度的平移后,我希望平移手势的状态变为UIGestureRecognizerStateBegan

我尝试插入touchesBegan并手动将状​​态设置为失败,然后在touchesMoved更新它以开始但我只想将其更改为开始一次(即它第一次到达阈值然后后续交互将是UIGestureRecognizerStateChanged

这可能吗?

2 个答案:

答案 0 :(得分:1)

这是一个似乎有效的子类。它延迟了#34;开始"状态,直到达到所需的距离。

DelayedPanGestureRecognizer.h:

#import <UIKit/UIKit.h>

@interface DelayedPanGestureRecognizer : UIPanGestureRecognizer

@property (nonatomic, assign) CGFloat delay;

@end

DelayedPanGestureRecognizer.m:

#import "DelayedPanGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>

@implementation DelayedPanGestureRecognizer

- (void)setState:(UIGestureRecognizerState)state {
    if (state == UIGestureRecognizerStateBegan) {
        CGPoint trans = [self translationInView:self.view];
        if (trans.x * trans.x + trans.y * trans.y > self.delay * self.delay) {
            [super setState:state];
        }
    } else {
        [super setState:state];
    }
}

@end

用法:

DelayedPanGestureRecognizer *pan = [[DelayedPanGestureRecognizer alloc] initWithTarget:self action:@selector(panned:)];
pan.delay = 6;
[someView addGestureRecognizer:pan];

行动:

- (void)panned:(DelayedPanGestureRecognizer *)gesture {
    NSLog(@"State: %d", (int)gesture.state);
    NSLog(@"%@", NSStringFromCGPoint([gesture translationInView:gesture.view]));

    if (gesture.state == UIGestureStateBegan) {
        // do something
    } else if (gesture.state == UIGestureStateChanged) {
        // do other things
    }
}

答案 1 :(得分:0)

// called when a gesture recognizer attempts to transition out of UIGestureRecognizerStatePossible. returning NO causes it to transition to UIGestureRecognizerStateFailed
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;

在满足条件之前,只需返回NO。