2012-10-25 33 views
0

我有一個rootViewController,在它的viewDidLoad方法,我初始化另外兩個ViewController2*對象及其作爲rootViewController.view子視圖的意見,然後我設置第一ViewController2* controller.view.hidden = YES如何中斷viewWillAppear中層次

然後,在v1上有一個按鈕處理程序,當它觸摸它時,它會呈現一個UINavigationController,然後在v1上觸摸'取消'按鈕調用dismissViewControllerAnimated

現在的問題是:當解僱完成後,兩個ViewController2*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 

ViewController2:

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

@end 

回答

0

viewWillAppear中會觸發你的UIViewController的,即使視圖控制器視圖設置隱藏= YES。

如果你想防止一些昂貴的操作發生,你可以肯定地測試你的viewWillAppear委託方法中的if(self.view.hidden == YES),但是要注意,如果你以後讓這個視圖不隱藏,viewWillAppear然後不會開火。

+0

是的,但這種情況很簡單,我可以測試是否隱藏= YES。但是,如果我有一個更復雜的情況:rootViewController - > ViewController2 - > ViewController3,ViewController2.view.hidden = YES,當關閉某些模式的viewController時,ViewController3的viewWillAppear仍然會觸發。我怎樣才能防止它發生? –

0

很簡單,這些方法被調用的原因是因爲viewController的視圖是主窗口視圖層次結構的一部分。這意味着它有一個超級視圖,超級視圖具有超級視圖,等等,直到超級視圖成爲主窗口。 而不是隱藏和取消隱藏viewController視圖,而應該添加並從他們的超級視圖中刪除它們。另外,要確保viewWillAppear和viewDidAppear在正確的時間被正確調用,請查看ViewController Containment: http://www.cocoanetics.com/2012/04/containing-viewcontrollers/