iOSDev
iOSDev

Reputation: 3617

Get Selected index of UITableView

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.

Upvotes: 106

Views: 86194

Answers (5)

davidrynn
davidrynn

Reputation: 2376

Swift 4.2

let selectedIndexPath = tableView.indexPathForSelectedRow

which is an optional return value.

Upvotes: 4

Nuzhdin Vladimir
Nuzhdin Vladimir

Reputation: 1832

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;
    }
}

Upvotes: 8

Vineesh TP
Vineesh TP

Reputation: 7973

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];

Upvotes: 5

Chris Gummer
Chris Gummer

Reputation: 4782

NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];

Upvotes: 219

Kolin Krewinkel
Kolin Krewinkel

Reputation: 1386

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.

Upvotes: 4

Related Questions