I am doing swipe gesture on UITableView
and want to know indexpath of cell on which my fingers are currently into i.e. swipe gestured performed from which cell.
I require indexPath
as I have to show information for that selected cell..
Thanks in advance..
add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.
For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.
So what you essentially need is to get the cell from swipe gesture on the table? Right.You dont need to know the indexPath
. First define swipe on the tableView
like so -
UISwipeGestureRecognizer *showExtrasSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellSwipe:)];
showExtrasSwipe.direction = UISwipeGestureRecognizerDirectionRight;
[tableView addGestureRecognizer:showExtrasSwipe];
[showExtrasSwipe release];
After this when the actual swipe happens you need to put handler to it. For that try this-
-(void)cellSwipe:(UISwipeGestureRecognizer *)gesture
{
CGPoint location = [gesture locationInView:tableView];
NSIndexPath *swipedIndexPath = [tableView indexPathForRowAtPoint:location];
UITableViewCell *swipedCell = [tableView cellForRowAtIndexPath:swipedIndexPath];
//Your own code...
}
So what we have done is first attach a SwipeGestureRecognizer
to the UITableView
(not the UITableViewCell
). After that when the swipe occurs on the UITableView
, I first get the co-ordinates of where the gesture occurred in the UITableView
. Next, using this coordinates I get the IndexPath
of the row of where swipe occurred in the UITableView
. Finally using the IndexPath
I get the UITableViewCell
. Simple really..
Note: I have been asked this far too many times. So adding this explanation of why I used SwipeGestureRecognizer
on the UITableView
and not on each individual UITableViewCell
.
I could have attached SwipeGestureRecognizer
to each UITableViewCell
. I did not do that since I would have had to attach a separate SwipeGestureRecognizer
for each cell. So If I had 1000 cells in my UITableView
I would have had to create 1000 SwipeGestureRecognizer
objects. This is not good. In my above approach I just create one SwipeGestureRecognizer
and thats it.
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