问题描述
我被卡住了!我不明白为什么viewWillAppear不运行在我的代码,但viewDidLoad运行。如果我理解它正确viewDidLoad运行一次在第一个实例和viewWillAppear运行每次视图添加到视图的堆栈显示。
I'm stuck! I can't see why viewWillAppear doesn't run in my code but viewDidLoad runs. If I understand it correctly viewDidLoad runs once on the first instance and viewWillAppear runs every time a view is added to the stack of views to display.
我看到其他人已经问题,但一些他们的解决方案调用viewWillAppear直接导致我的应用程序崩溃。其他解决方案涉及到Navigation Controller和pushingView的,但这不是我使用了!我缺少什么?
I see others have had this issue but some how their solutions of calling viewWillAppear directly causes my app to crash. Other solutions were related to Navigation Controller and pushingView's but thats not what i'm using either! What am I missing?
感谢您的帮助! :)
如下:
View Controller#1 - 目前显示在屏幕上
See below:View Controller #1 - Currently being displayed on screen
-(IBAction)someButtonPressed:(id)sender{
NSLog(@"FirstViewController - someButtonPressed");
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
secondViewController.myLocation = self.myLocation;
secondViewController.myDatabase = self.myDatabase;
[self.view addSubview:secondViewController.view];
//[secondViewController viewWillAppear:YES];
}
SecondViewController:
SecondViewController:
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"SecondViewController - viewWillAppear");
[super viewWillAppear:animated];
// updating ivars with data
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(@"SecondViewController - viewDidLoad");
[super viewDidLoad];
}
推荐答案
每次加载UIViewController的视图时都会调用
-viewDidLoad
。在单个控制器的生命期间,这可能是很多次,因为视图可能被卸载以释放内存,当它不可见和重新加载,触发另一个调用 -viewDidLoad
,当需要时。当UIViewController的视图变为可见时,调用
-viewDidLoad
is called every time a UIViewController's view is loaded. That may be many times during a single controller's life as the view may be unloaded to free up memory when it is not visible and reloaded, triggering another call to -viewDidLoad
, when needed.
-viewWillAppear:
。然而UIKit假设UIViewController的视图将填充他们的窗口。嵌套UIViewControllers的视图是的示例,将导致意外的行为。如您所见。
-viewWillAppear:
is called when a UIViewController's view becomes visible. However UIKit assumes that UIViewController's views will fill their window. Nesting UIViewControllers' views is an example of abusing UIViewControllers and will result in unexpected behavior. As you have seen.
请参阅在iOS控制器编程指南中:
See About Custom View Controllers in the View Controller Programming Guide for iOS:
这篇关于viewWillAppear在使用addSubView时不运行!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!