James James - 2 months ago 15
iOS Question

UITableView programmatically select option

I have a view that has several options, and inside it is a table view that gets data from a server.

Is there a way to have the table view automatically select the first option on load, i.e. in

viewDidLoad
?

Answer Source

Try UITableView's selectRowAtIndexPath:animated:scrollPosition: method.

- (void)viewDidLoad {
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
}

If you want the delegate callback, you'll have to call it manually:

if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
    [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

You'd probably want to cache that index path in a local variable, then.