I have an application that is viewbased and I am adding a tableview as a subview to the main view. I have taken UITableViewDelegate
to respond the table methods.
To only select the first cell the first time the table is loaded, one would think that using viewDidLoad
is the right place to go, but, at that time of execution, the table hasn't loaded its contents, so it will not work (and probably crash the app since the NSIndexPath
will point to a non-existent cell).
A workaround is to use a variable that indicates that the table has loaded before and do the work accordingly.
@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