Is it possible to determine whether ViewController is presented as Modal?

后端 未结 14 2190
一生所求
一生所求 2020-12-04 07:13

Is it possible to check inside ViewController class that it is presented as modal view controller?

14条回答
  •  没有蜡笔的小新
    2020-12-04 07:55

    If you a looking for iOS 6+, this answer is deprecated and you should check Gabriele Petronella's answer


    There is no neat way to do that, as a property or method native to UIKit. What you can do is to check several aspects of your controller to ensure it is presented as modal.

    So, to check if the current (represented as self in the code bellow) controller is presented in a modal way or not, I have the function bellow either in a UIViewController category, or (if your project does not need to use other UIKit controllers, as UITableViewController for example) in a base controller that my other controllers inherit of

    -(BOOL)isModal {
    
         BOOL isModal = ((self.parentViewController && self.parentViewController.modalViewController == self) || 
                //or if I have a navigation controller, check if its parent modal view controller is self navigation controller
                ( self.navigationController && self.navigationController.parentViewController && self.navigationController.parentViewController.modalViewController == self.navigationController) || 
                //or if the parent of my UITabBarController is also a UITabBarController class, then there is no way to do that, except by using a modal presentation
                [[[self tabBarController] parentViewController] isKindOfClass:[UITabBarController class]]);
    
        //iOS 5+
        if (!isModal && [self respondsToSelector:@selector(presentingViewController)]) {
    
            isModal = ((self.presentingViewController && self.presentingViewController.modalViewController == self) || 
                 //or if I have a navigation controller, check if its parent modal view controller is self navigation controller
                 (self.navigationController && self.navigationController.presentingViewController && self.navigationController.presentingViewController.modalViewController == self.navigationController) || 
                 //or if the parent of my UITabBarController is also a UITabBarController class, then there is no way to do that, except by using a modal presentation
                 [[[self tabBarController] presentingViewController] isKindOfClass:[UITabBarController class]]);
    
        }
    
        return isModal;        
    
    }
    

    EDIT: I added the last check to see if a UITabBarController is being used, and you present another UITabBarController as modal.

    EDIT 2: added iOS 5+ check, where UIViewController does not answer for parentViewController anymore, but to presentingViewController instead.

    EDIT 3: I've created a gist for it just in case https://gist.github.com/3174081

提交回复
热议问题