105

I want to have selected index for UITableView. I have written following code:

NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0];
[tableView scrollToRowAtIndexPath:index 
                 atScrollPosition:UITableViewScrollPositionTop 
                         animated:YES];

This always work for 1st item. I want to have selected index in indexPathForRow.

Please help. Thanks.

Alex Cio
  • 5,752
  • 4
  • 40
  • 73
iOSDev
  • 3,607
  • 10
  • 49
  • 90

5 Answers5

218
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
Chris Gummer
  • 4,752
  • 1
  • 21
  • 17
  • 5
    If you allow multiple selections, consider using: - (NSArray *)indexPathsForSelectedRows – yura Feb 19 '15 at 19:12
  • Once you have that `*selectedIndexPath` it is useful for me to have access to `long pathRow = [selectedIndexPath row];` and `long pathSection = [selectedIndexPath section];` when you need specific selections (note that `NSInteger` is a `typedef long` which coming from a C background makes more sense since both need `%ld` anyway. – Jonathan Weinraub Apr 03 '20 at 15:12
8

Get current selected row. May be helpful if you have only one section.

- (NSUInteger)currentSellectedRowIndex
{
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    if (selectedIndexPath) {
        return selectedIndexPath.row;
    }
    else {
        return NSNotFound;
    }
}
Nuzhdin Vladimir
  • 1,373
  • 17
  • 29
5

Use this code

CGPoint location =[sender locationInView:self.tableView];
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:location];
UITableViewCell *swipedCell  = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
NSIndexPath *indexPath = [self.tableView indexPathForCell:swipedCell];
Vineesh TP
  • 7,025
  • 9
  • 54
  • 102
4

In didSelectRowAtIndexPath, set an interface declared NSIndexPath as the indexpath returned. Then you can scroll to that variable. If you need help, comment and I can give some sample code.

Kolin Krewinkel
  • 1,376
  • 11
  • 12
  • Alternatively, you can use Chris's method for quicker use. The above method offers more control and can be modified by your (example) detail view controller. – Kolin Krewinkel Oct 27 '10 at 23:04
3

Swift 4.2

let selectedIndexPath = tableView.indexPathForSelectedRow

which is an optional return value.

davidrynn
  • 1,788
  • 16
  • 20