I want to be able to swipe left or right anywhere in a table view cell to erase the cell of with animation without showing the delete button. How can I do this?
I have not tried and implemented this, but I'll give it a shot. First, create a custom UITableViewCell, and let it have 2 properties that you can use
In your cellForRowAtIndexPath:
, where you create the custom cell, set these properties. Also add a UISwipeGestureRecognizer to the cell
cell.tableView=tableView;
cell.indexPath=indexPath;
UISwipeGestureRecognizer *swipeGestureRecognizer=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(deleteCell:)];
[cell addGestureRecognizer:swipeGestureRecognizer];
[swipeGestureRecognizer release];
Make sure that the gesture only receives horizontal swipes.
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([[gestureRecognizer view] isKindOfClass:[UITableViewCell class]]&&
((UISwipeGestureRecognizer*)gestureRecognizer.direction==UISwipeGestureRecognizerDirectionLeft
||(UISwipeGestureRecognizer*)gestureRecognizer.direction==UISwipeGestureRecognizerDirectionRight)) return YES;
}
In your deleteCell:
-(void) deleteCell:(UIGestureRecognizer*)gestureRec
{
UIGestureRecognizer *swipeGestureRecognizer=(UISwipeGestureRecognizer*)gestureRec;
CustomCell *cell=[swipeGestureRecognizer view];
UITableView *tableView=cell.tableView;
NSIndexPath *indexPath=cell.indexPath;
//you can now use these two to perform delete operation
}
The solution posted by @MadhavanRP works, but it is more complex than it needs to be. You could take a simpler approach and create one gesture recognizer that handles all swipes that occur in the table, and then get the location of the swipe to determine what cell the user swiped.
To setup the gesture recognizer:
- (void)setUpLeftSwipe {
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(swipeLeft:)];
[recognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.tableView addGestureRecognizer:recognizer];
recognizer.delegate = self;
}
Call this method in viewDidLoad
To handle the swipe:
- (void)swipeLeft:(UISwipeGestureRecognizer *)gestureRecognizer {
CGPoint location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
... do something with cell now that i have the indexpath, maybe save the world? ...
}
note: your vc must implement the gesture recognizer delegate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With