Markus Markus - 4 months ago 19
iOS Question

How to know if a view controller will be presented as a popover or modal?

Before presenting a view controller I set the

modalPresentationStyle
property to
UIModalPresentationPopover
. This will present the view controller as a popover when running on devices with a regular horizontal size class (iPad and iPhone 6+ in landscape) and as modal/fullscreen on other devices. It's also possible to override this behaviour by overriding
adaptivePresentationStyleForPresentationController
so that the view controller is presented as a popover on all devices.

I wonder if it's possible, after a view controller is presented, to know if it's presented as a popover or not? Just looking at the size class won't do it as it's possible that the view controller overrides
adaptivePresentationStyleForPresentationController
.

The obvious answer would be that I, as the programmer, should know if I override
adaptivePresentationStyleForPresentationController
or not but I want to write a function that can determine this in runtime for any view controller by passing in the view controller or maybe the
UIPopoverPresentationController
(or any other object needed) as an argument.

Here's some code to present the view controller:

navigationController = (UINavigationController *)[MVSStore sharedInstance].addViewController;
navigationController.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:navigationController animated:YES completion:^{}];

UIPopoverPresentationController *popoverController = navigationController.popoverPresentationController;
popoverController.sourceView = self.view;
popoverController.sourceRect = CGRectMake(20, 20, 20, 20); // Just a dummy
popoverController.permittedArrowDirections = UIPopoverArrowDirectionAny;


Here's the current code to detect if the view controller is presented as a popover or not. But as mentioned above it just looks at the size class which doesn't work for all cases.

+ (BOOL)willPresentTruePopover:(id<UITraitEnvironment>)vc {
return ([vc traitCollection].horizontalSizeClass == UIUserInterfaceSizeClassRegular);
}


I cannot find any property or function in
UIViewController
or
UIPopoverPresentationController
(or anywhere else) that gives me this information right away but maybe I'm missing something?

Answer

Use the UIAdaptivePresentationControllerDelegate method presentationController:willPresentWithAdaptiveStyle:transitionCoordinator:. To query the presentation style at other times, ask the presentation controller for its adaptivePresentationStyleForTraitCollection:, passing the current traits. These methods were added in iOSĀ 8.3, and are not documented yet.

Comments