7

I have a UITableViewController in my app, which is added to the view hierarchy directly. After the view appears, I want to scroll to a specific cell. My solution would be to call the code for scrolling in -[viewDidAppear].

According to Apple's docs I have to call the method manually:

If the view belonging to a view controller is added to a view hierarchy directly, the view controller will not receive this message. If you insert or add a view to the view hierarchy, and it has a view controller, you should send the associated view controller this message directly.

The question is: When is the right time to call it manually?

Calling it from the parent view controller's -[viewDidAppear] leads to a crash when I try to do the scrolling because apparently, the table view actually didn't yet appear and therefore thinks it has no sections to scroll to.

4

4 回答 4

19

如果您使用的是视图控制器包含,请不要viewWillAppear:直接调用。而是使用– beginAppearanceTransition:animated:– endAppearanceTransition

如果您正在实现自定义容器控制器,请使用此方法告诉孩子它的视图即将出现或消失。不要直接调用 viewWillAppear:、viewWillDisappear:、viewDidAppear: 或 viewDidDisappear:。

调用 addSubView 会自动触发viewWillAppear:viewDidAppear:如果视图的 viewController 是子视图控制器,viewWillAppear:直接调用会触发两次 view will appearance 方法。使用 beginAppearanceTransition:animated: and– endAppearanceTransition` 将抑制自动行为,因此您只会调用一次。

于 2014-07-30T09:22:48.217 回答
1

在tableview上的-[viewDidAppear]中,确实是从父视图控制器的-[viewDidAppear]调用的,你可以调用[tableView reloadData],这样你就可以确保tableView已经加载并准备好了。

于 2009-09-22T17:59:05.203 回答
0

这就是我手动调用viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear:这里的方式

并且我以这种方式加载的视图控制器之一具有以下内容viewWillAppear:(请注意,这是viewWillAppear因为在viewDidAppear被调用的点上,用户可以查看您的视图)

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [wordListTable reloadData];
    [wordListTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
}
于 2009-09-23T08:14:02.417 回答
0

从父控制器的-viewDidAppear调用它通常是您最好的选择。

如果在子视图控制器尚未完全初始化的情况下这会导致问题,那么您可能会遇到另一个问题。确保您的子视图控制器在调用-viewWillAppear后完全“准备就绪” (您也可以从父级的-viewWillAppear手动调用)

于 2009-09-22T17:59:03.090 回答