Get Selected index of UITableView
84,967
Solution 1
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
Solution 2
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;
}
}
Solution 3
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];
Solution 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.
Solution 5
Swift 4.2
let selectedIndexPath = tableView.indexPathForSelectedRow
which is an optional return value.
Related videos on Youtube
Comments
-
iOSDev almost 2 years
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.
-
Kolin Krewinkel over 13 yearsAlternatively, 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.
-
yura over 9 yearsIf you allow multiple selections, consider using: - (NSArray *)indexPathsForSelectedRows
-
Jonathan Weinraub about 4 yearsOnce you have that
*selectedIndexPath
it is useful for me to have access tolong pathRow = [selectedIndexPath row];
andlong pathSection = [selectedIndexPath section];
when you need specific selections (note thatNSInteger
is atypedef long
which coming from a C background makes more sense since both need%ld
anyway. -
AntonSack over 3 yearsStraight and simple. Thanks!