Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 449
Baub Avatar asked May 31 '26 22:05

Baub


1 Answers

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.

like image 122
FeifanZ Avatar answered Jun 02 '26 14:06

FeifanZ