当前可见视图控制器检查

时间:2013-04-29 10:42:59

标签: ios iphone objective-c uiviewcontroller

我正在AppDelegate课程中查看我的ParentEndViewController目前是否为可见课程。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle: nil];  
ParentEndViewController *parent = [storyboard instantiateViewControllerWithIdentifier:@"ParentEndViewController"];
 if (parent.isViewLoaded && parent.view.window){
         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
                                                            message:body
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
        NSLog(@"current view is parent!");
    }
    else{
        NSLog(@"current view is not parent!");
    }

正在打印current view is not parent!“。但我确信我的应用程序上运行的当前视图为ParentEndViewController,即应打印current view is parent!

问题出在哪里?

3 个答案:

答案 0 :(得分:5)

问题是,当您调用ParentEndViewController时,您实例化[storyboard instantiateViewControllerWithIdentifier:@"ParentEndViewController"];的新对象,此实例与根视图控制器的实例不同。 如果您要在应用代理中检查应用的根视图控制器,则应尝试

if([self.window.rootViewController isKindOfClass:[ParentEndViewController class]]) {
    NSLog(@"Luke I'm your father");
}
else {
    NSLog(@"Sorry bro, somebody else is the parent");
}

如果要检查导航控制器的最后一个视图控制器,则应尝试以下操作:

UIViewController *lastViewController = [[self.navigationController viewControllers] lastObject];

 if([lastViewController isKindOfClass:[ParentEndViewController class]) {
       NSLog(@"Luke I'm your father");
 }
 else {
     NSLog(@"Sorry bro, somebody else is the parent");
 }

答案 1 :(得分:3)

您可以通过window属性进行检查:

if(viewController.view.window){

     // view visible

}else{

    // no visible

}

答案 2 :(得分:0)

我想当你在Appdelegate中检查时,ParentEndViewController不是当前视图,因为应用程序仍然停留在加载过程中。

如果将该代码放入ParentEndViewController的viewDidAppear中,您应该得到正确的结果。