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

后端 未结 14 2173
一生所求
一生所求 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 08:02

    I've looked a bit around to find the right answer to this question, and I couldn't find any which covered all the possible scenarios. I wrote these few lines of code which seem to do the job. You can find few inline comments to figure out what's been checked.

    - (BOOL)isModal {
        BOOL modal = NO;
        if ([self presentingViewController]) { //Some view Controller is presenting the current stack
            UIViewController *presented = [[self presentingViewController] presentedViewController]; // What's been presented
            if ([presented respondsToSelector:@selector(viewControllers)]) { // There's a stack
                NSArray *viewControllers = [presented performSelector:@selector(viewControllers)];
                modal = [viewControllers firstObject] == self; // Current VC is presented modally if it's the first in the stack
            }
            else {
                modal = presented == self; // Don't think this is actually needed. set modal = YES should do the job tho.
            }
        }
        return modal;
    }
    

    Hope this help.

提交回复
热议问题