1

我有一个rootViewController,在它的方法中,我将另外两个对象和它们的视图viewDidLoad初始化为的子视图,然后我先设置。ViewController2*rootViewController.viewViewController2* controller.view.hidden = YES

然后,在 v1 上有一个按钮处理程序,当触摸它时,它会呈现一个 UINavigationController,然后在 v1 上触摸“关闭”按钮调用dismissViewControllerAnimated

问题是:当dismiss完成时,两个ViewController2*fire viewWillAppear。如何让它只viewWillAppear在可见的那个上开火,而不是在隐藏的那个上开火?

rootViewController实现:

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.v1 = [[ViewController2 alloc] init];
self.v1.title = @"v1";
[self.view addSubview:self.v1.view];
self.v1.view.hidden = YES;

self.v2 = [[ViewController2 alloc] init];
self.v2.title = @"v2";
[self.view addSubview:self.v2.view];

UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"POP" forState:UIControlStateNormal];
[btn sizeToFit];
[btn addTarget:self action:@selector(touchHandler:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:btn];
}

- (void)touchHandler:(id)sender {
UINavigationController * nc= [[UINavigationController alloc] initWithRootViewController:[[UIViewController alloc] initWithNibName:nil bundle:nil]];

((UIViewController *)[nc.viewControllers objectAtIndex:0]).navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"dismiss" style:UIBarButtonItemStyleBordered target:self action:@selector(dismissHandler:)];

[self presentViewController:nc animated:YES completion:nil];
}

- (void) dismissHandler:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end

视图控制器2:

@implementation ViewController2
- (void)viewWillAppear:(BOOL)animated
{
NSLog(@"%@",self.title);
}

@end
4

2 回答 2

0

很简单,调用这些方法的原因是因为 viewController 的视图是主窗口视图层次结构的一部分。这意味着它有一个 superview 有一个 superview 有一个 superview 等等,直到这个 superview 是主窗口。与其隐藏和取消隐藏 viewController 视图,不如在其父视图中添加和删除它们。此外,为了确保在正确的时间正确调用 viewWillAppear 和 viewDidAppear,请查看 ViewController Containment: http ://www.cocoanetics.com/2012/04/ contains-viewcontrollers/

于 2012-10-26T11:25:41.150 回答
0

viewWillAppear 将在您的 UIViewController 上触发,即使视图控制器视图设置为 hidden=YES。

如果您想防止发生一些昂贵的操作,您当然可以在您的 viewWillAppear 委托方法中测试 if (self.view.hidden == YES),但请注意,如果您稍后取消隐藏该视图,该 viewWillAppear 将不会触发然后。

于 2012-10-25T18:03:54.147 回答