你可曾遇到過viewWillAppear沒有被調用到的情況
產生原因是用了UINavigationController. 將UINavigationController的view作為subview添加到了其他viewController的view中。或者把UINavigationController添加到UITabbarController中了。此時,NavigationController的stack里面的viewController就收不到-(void)viewWillAppear:(BOOL)animated;等4個方法的調用。
原因呢
Apple 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.
不過后面的到4.0的文檔就沒有發現這樣的文字描述了,但是還是沒能夠調用的到這樣
只是添加的更復雜的文檔,頭暈暈看不下去了。
解決方法兩種:
-
在導航控制器上層controller的viewWillAppear中顯式調用viewWillAppear方法。
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[subNavCntlr viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[subNavCntlr viewWillDisappear:animated];
}
2. 把導航控制器上層controller設為UINavigationController的delegate
nav.delegate = self;
@interface RootViewController : UIViewController
<UINavigationControllerDelegate> { UINavigationController
*navController;}
- (void)navigationController:(UINavigationController
*)navigationController willShowViewController:(UIViewController
*)viewController animated:(BOOL)animated {
[viewController viewWillAppear:animated];
} - (void)navigationController:(UINavigationController
*)navigationController didShowViewController:(UIViewController
*)viewController animated:(BOOL)animated {
[viewController viewDidAppear:animated];
}