To select the first cell when loading the table for the first time, you might think that using viewDidLoad is the right place to go, but at that time the table hasnโt loaded its contents, so it wonโt work (and, possibly, the application crashes , since NSIndexPath will point to a nonexistent cell).
The workaround is to use a variable that indicates that the table was loaded before and was doing the appropriate work.
@implementation MyClass { BOOL _tableHasBeenShownAtLeastOnce; } - (void)viewDidLoad { [super viewDidLoad]; _tableHasBeenShownAtLeastOnce = NO; // Only on first run } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if ( ! _tableHasBeenShownAtLeastOnce ) { _tableHasBeenShownAtLeastOnce = YES; BOOL animationEnabledForInitialFirstRowSelect = YES; // Whether to animate the selection of the first row or not... in viewDidAppear:, it should be YES (to "smooth" it). If you use this same technique in viewWillAppear: then "YES" has no point, since the view hasn't appeared yet. NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection: 0]; [self.tableView selectRowAtIndexPath:indexPathForFirstRow animated:animationEnabledForInitialFirstRowSelect scrollPosition:UITableViewScrollPositionTop]; } } /* More Objective-C... */ @end
Alejandro Ivรกn 05 Oct '15 at 19:40 2015-10-05 19:40
source share