Swipe gestures on UITableView
, Andreas KatzianUser interactions on table cells don’t have to be necessarily restricted to simply scroll and tap them. However, with some additional code and the support of gesture recognizers introduced in iOS 3.2 you can give your users the possibility to swipe on your table view cells for exciting additional actions. A common task for that would be to implement a swipe gesture for removing a single item within your table view (seen on several task management and todo apps) or simply changing the state of an item.
All you need is some pretty forward code like the following, which basically creates two gesture recognizers to handle left and right swipes on your table. As you can see we add these gesture recognizers directly to a UITableView rather than to single UITableViewCells.
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"Your controller title";
//Add a left swipe gesture recognizer
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSwipeLeft:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.tableView addGestureRecognizer:recognizer];
[recognizer release];
//Add a right swipe gesture recognizer
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSwipeRight:)];
recognizer.delegate = self;
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.tableView addGestureRecognizer:recognizer];
[recognizer release];
}
The called methods of the gesture recognizers look like as stated below. From the gesture recognizer you’ll get the point of the start of the swipe gesture and with the indexPathForRowAtPoint: method you can get the correct index path for the UITableViewCell the swipe was performed on. From this point on it is up to you to perform more functionality to your table view cell.
- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
//Get location of the swipe
CGPoint location = [gestureRecognizer locationInView:self.tableView];
//Get the corresponding index path within the table view
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
//Check if index path is valid
if(indexPath)
{
//Get the cell out of the table view
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//Update the cell or model
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)gestureRecognizer
{
//same code for getting UITableViewCell like before
}
comments powered by Disqus