Swipe gestures in a UITableView

When we have a UITableView, sometimes we want to add some actions when the user swipes over a row of the table. We can capture swipes to the left, right, down or up directions.
To capture both left and right swipe gestures, add the following code to your UITableViewController in the viewDidLoad method.

UISwipeGestureRecognizer *gestureLeft = [[UISwipeGestureRecognizer alloc] 
     initWithTarget:self 
     action:@selector(handleSwipeLeft:)];
[gestureLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.tableView addGestureRecognizer:gestureLeft];
    
UISwipeGestureRecognizer *gestureRight = [[UISwipeGestureRecognizer alloc] 
     initWithTarget:self 
     action:@selector(handleSwipeRight:)];
[gestureRight setDelegate:self];
[gestureRight setDirection:UISwipeGestureRecognizerDirectionRight];
[self.tableView addGestureRecognizer:gestureRight];

The action parameter indicates the method that will be executed when the gesture is recognized. We have to include these methods in our controller too.


- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    
    // Action...
}

- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    
    // Action...
}

The method locationInView returns the location of the gesture, represented as a point in the local coordinate system of the view. Using the indexPathForRowAtPoint method of the UITableView object, we can obtain the row of the gesture.

We could use also the same action method to handle all the swipe gestures. Change the action methods from handleSwipeLeft and handleSwipeRight to handleSwipe, and add the following method instead.

- (void)handleSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];

    switch ([gestureRecognizer direction]) {
        case UISwipeGestureRecognizerDirectionLeft:
            // Action
            break;
        case UISwipeGestureRecognizerDirectionRight:
            // Action
            break;
        default:
            break;
    }
}
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.