Чтобы выбрать первую ячейку только при первой загрузке таблицы, можно подумать, что использование viewDidLoad
- правильное место, , но , в этот момент выполнения таблица не имела t загрузил его содержимое, поэтому оно не будет работать (и, вероятно, приведет к сбою приложения, поскольку NSIndexPath
будет указывать на несуществующую ячейку).
Обходной путь - использовать переменную, которая указывает, что таблица загружена ранее, и выполнять работу соответствующим образом.
@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