How to present UIAlertController when not in a view controller?

前端 未结 30 3124
庸人自扰
庸人自扰 2020-11-22 06:21

Scenario: The user taps on a button on a view controller. The view controller is the topmost (obviously) in the navigation stack. The tap invokes a utility class method call

30条回答
  •  终归单人心
    2020-11-22 06:50

    Kevin Sliech provided a great solution.

    I now use the below code in my main UIViewController subclass.

    One small alteration i made was to check to see if the best presentation controller is not a plain UIViewController. If not, it's got to be some VC that presents a plain VC. Thus we return the VC that's being presented instead.

    - (UIViewController *)bestPresentationController
    {
        UIViewController *bestPresentationController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
        if (![bestPresentationController isMemberOfClass:[UIViewController class]])
        {
            bestPresentationController = bestPresentationController.presentedViewController;
        }    
    
        return bestPresentationController;
    }
    

    Seems to all work out so far in my testing.

    Thank you Kevin!

提交回复
热议问题