iPhone viewWillAppear not firing

2019-01-01 14:33发布

I've read numerous posts about people having problems with viewWillAppear when you do not create your view hierarchy just right. My problem is I can't figure out what that means.

If I create a RootViewController and call addSubView on that controller, I would expect the added view(s) to be wired up for viewWillAppear events.

Does anyone have an example of a complex programmatic view hierarchy that successfully receives viewWillAppear events at every level?

Apple's Docs state:

Warning: 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. Failing to send the view controller this message will prevent any associated animation from being displayed.

The problem is that they don't describe how to do this. What does "directly" mean? How do you "indirectly" add a view?

I am fairly new to Cocoa and iPhone so it would be nice if there were useful examples from Apple besides the basic Hello World crap.

21条回答
若你有天会懂
2楼-- · 2019-01-01 15:15

I just had this problem myself and it took me 3 full hours (2 of which googling) to fix it.

What turned out to help was to simply delete the app from the device/simulator, clean and then run again.

Hope that helps

查看更多
旧人旧事旧时光
3楼-- · 2019-01-01 15:17

In case this helps anyone. I had a similar problem where my ViewWillAppear is not firing on a UITableViewController. After a lot of playing around, I realized that the problem was that the UINavigationController that is controlling my UITableView is not on the root view. Once I fix that, it is now working like a champ.

查看更多
临风纵饮
4楼-- · 2019-01-01 15:19

If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.

You need to use the navigation controller delegate methods instead:

navigationController:willShowViewController:animated:
navigationController:didShowViewController:animated:
查看更多
倾城一夜雪
5楼-- · 2019-01-01 15:23

I've run into this same problem. Just send a viewWillAppear message to your view controller before you add it as a subview. (There is one BOOL parameter which tells the view controller if it's being animated to appear or not.)

[myViewController viewWillAppear:NO];

Look at RootViewController.m in the Metronome example.

(I actually found Apple's example projects great. There's a LOT more than HelloWorld ;)

查看更多
流年柔荑漫光年
6楼-- · 2019-01-01 15:25

A very common mistake is as follows. You have one view, UIView* a, and another one, UIView* b. You add b to a as a subview. If you try to call viewWillAppear in b, it will never be fired, because it is a subview of a

查看更多
永恒的永恒
7楼-- · 2019-01-01 15:26
[self.navigationController setDelegate:self];

Set the delegate to the root view controller.

查看更多
登录 后发表回答