How can I fix the "UIPopoverController is deprecated" warning?

Varun Naharia picture Varun Naharia · Sep 28, 2015 · Viewed 45.4k times · Source

I am using this code:

mediaLibraryPopover = [[UIPopoverController alloc] 
                        initWithContentViewController:avc];
[self.mediaLibraryPopover presentPopoverFromRect:[theButton bounds] 
                          inView:theButton 
                          permittedArrowDirections:UIPopoverArrowDirectionAny 
                          animated:YES];

And I am getting this warning in Xcode 7:

UIPopoverController is deprecated, first deprecated in iOS 9.0 - UIPopoverController is deprecated. Popovers are now implemented as UIViewController presentations. Use a modal presentation style of UIModalPresentationPopover and UIPopoverPresentationController.

Answer

Midhun MP picture Midhun MP · Sep 28, 2015

You no longer need UIPopoverController for presenting a view controller. Instead you can set the modalPresentationStyle of view controller to UIModalPresentationPopover.

You can use the following code for that:

avc.modalPresentationStyle = UIModalPresentationPopover;
avc.popoverPresentationController.sourceView = theButton;
[self presentViewController:avc animated:YES completion:nil];

UIModalPresentationPopover

In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.

Reference UIModalPresentationStyle Reference


You need to set either sourceView or barButtonItem property, else it will crash with the following message:

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (***) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'

For anchoring the popover arrow correctly, you need to specify the sourceRect property also.

avc.modalPresentationStyle                   = UIModalPresentationPopover;
avc.popoverPresentationController.sourceView = self.view;
avc.popoverPresentationController.sourceRect = theButton.frame;
[self presentViewController:avc animated:YES completion:nil];

Refer sourceView and sourceRect for more details.