Pregunta

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..

¿Fue útil?

Solución

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.

Otros consejos

If you are trying to implement 'swipe to delete' (swipe in the horizontal direction), you do not need to re-invent the wheel. Simply uncomment the method commitEditingStyle:forRowAtIndexPath: in your UITableViewController delegate.

Did you checked this source code? : https://github.com/thermogl/TISwipeableTableView

That really might help you, this is a full implementation of a "swipeable" tableview...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top