How to detect a swipe event in a UITableViewCell with a UISwipeGestureRecognizer

*爱你&永不变心* 提交于 2019-12-08 12:57:56

问题


I have a UITableViewCell class where I want to detect the swipe event (delete) in order to hide some graphics drawn in the drawRect

First I added a UISwipeGestureRecognice to the cell:

// Init swipe gesture recognizer
self.swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeCell:)];
self.swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight;
self.swipeRecognizer.delegate = self;
[self.contentView addGestureRecognizer:self.swipeRecognizer];

Than I implemented a method to react on the swipe event:

- (void)swipeCell:(UISwipeGestureRecognizer *)recognizer
{
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            self.swipeStartPoint = [recognizer locationInView:self.backgroundView];
            BaseLogDebug(INFO, @"Swipe Began at %@", NSStringFromCGPoint(self.swipeStartPoint));
            break;
        case UIGestureRecognizerStateChanged: {
            CGPoint currentPoint = [recognizer locationInView:self.backgroundView];
            CGFloat deltaX = currentPoint.x - self.swipeStartPoint.x;
            BaseLogDebug(INFO, @"Swipe Moved %f", deltaX);
        }
            break;
        case UIGestureRecognizerStateEnded:
            BaseLogDebug(INFO, @"Swipe Ended");
            break;
        case UIGestureRecognizerStateCancelled:
            BaseLogDebug(INFO, @"Swipe Cancelled");
            break;
        default:
            break;
    }
}

In order to allow simultaneous gesture recognizer I implemented the following method:

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
 shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

The only state the gesture recognize recognizes is the state UIGestureRecognizerStateEnded. What's wrong with my code?


回答1:


From the UIGestureRecognizer Class Reference docs:

Recognizers for discrete gestures transition from UIGestureRecognizerStatePossible to UIGestureRecognizerStateFailed or UIGestureRecognizerStateRecognized.

and

Gesture recognizers recognize a discrete event such as a tap or a swipe but don’t report changes within the gesture. In other words, discrete gestures don’t transition through the Began and Changed states and they can’t fail or be cancelled.

UISwipeGestureRecognizer is a discrete gesture. If you want a continuous (but similar) gesture, use a UIPanGestureRecognizer instead.



来源:https://stackoverflow.com/questions/25253772/how-to-detect-a-swipe-event-in-a-uitableviewcell-with-a-uiswipegesturerecognizer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!