Select tableview row programmatically
How do I programmatically select a UITableView
row so that
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
gets executed? selectRowAtIndexPath
will only highlight the row.
Like Jaanus told:
Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.
So you just have to call the delegate
method yourself.
For example:
Swift 3 version:
let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)
ObjectiveC version:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath
animated:YES
scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
Swift 2.3 version:
let indexPath = NSIndexPath(forRow: 0, inSection: 0);
self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
From reference documentation:
Calling this method does not cause the delegate to receive a
tableView:willSelectRowAtIndexPath:
ortableView:didSelectRowAtIndexPath:
message, nor does it sendUITableViewSelectionDidChangeNotification
notifications to observers.
What I would do is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self doSomethingWithRowAtIndexPath:indexPath];
}
And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.