My Kill Death Ratio iPhone app lets you swipe on a cell in order to reveal an edit button and a delete button. I never liked how it worked in practice, however, because it was very finicky. You had to be very precise with your swipe, otherwise it would just register as a tap on the cell, and you would be brought to a different screen. Very frustrating. Through some research on stackoverflow.com, I realized last night that I was doing it totally wrong.
What I was doing before was to put a gesture recognizer on every UITableViewCell’s contentView. What I should have been doing instead was to put the gesture recognizer on the UITableView itself. Like so:
UISwipeGestureRecognizer * swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeLeft:)];
swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onSwipeRight:)];
One of the samples I found used one shared gesture recognizer for both left and right swipes. And then it tried to figure out which direction was swiped in the delegate method. But that didn’t work for me, so I created two gesture recognizers.
The next trick was to find out which table cell was swiped, which I also found on stackoverflow.com:
- (void) onSwipeLeft:(UISwipeGestureRecognizer *)recognizer
if (recognizer.state == UIGestureRecognizerStateEnded)
CGPoint swipeLocation = [recognizer locationInView:_tableView];
NSIndexPath *swipedIndexPath = [_tableView indexPathForRowAtPoint:swipeLocation];
UITableViewCell *swipedCell = [_tableView cellForRowAtIndexPath:swipedIndexPath];
// do what you want here
Now the swiping in my app works much better. Here’s the post on stackoverflow.com that helped me the most.
Leave a comment