Baub
Baub

Reputation: 5044

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?

Upvotes: 3

Views: 5905

Answers (2)

Chaitanya Gupta
Chaitanya Gupta

Reputation: 4053

To select a row, you can use the instance method selectRowAtIndexPath:animated:scrollPosition: of UITableView to select a row.

But why do you want to do it in viewDidLoad?

Upvotes: 1

FeifanZ
FeifanZ

Reputation: 16316

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.

Upvotes: 12

Related Questions