Self-sizing Popovers

How do you control the size of a popover? What if you want the popover to size itself to fit the content?

Preferred Content Size

When you use a popover presentation style the system provides a default size for the content. The size depends on the device and available space and may not be what you want. In this case I have a text label and an image view. In landscape on an iPad Pro (11-inch) the popover has a default size which is larger than I want:

Default popover presentation

If you’re presenting a view controller in a popover you can set a preferred size for the popover. You set the preferredContentSize property on the presented view controller. If you’re using a storyboard you’ll find it in the attributes inspector:

Setting explicit content size in attributes inspector

Or if you prefer, set it in the view controller (for example, in viewDidLoad) or when presenting the view controller:

preferredContentSize = CGSize(width: 300, height: 300)

That’s fine but what if I want to size the popover to exactly fit the content of my view controller?

Self-Sizing A Popover To Fit The Content

We can use the same technique we used when self-sizing child views. The preferredContentSize allows a child view controller to tell a parent container view controller the size it wants to be. In this case the parent container view is a popover presentation controller.

Assuming we have used Auto Layout to fully constrain our content we can calculate the fitting size and use that to size the popover. In the viewDidLoad method of my content view controller:

preferredContentSize = view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

Using systemLayoutSizeFitting on the root view of the view controller asks the Auto Layout engine to calculate the smallest (layoutFittingCompressedSize) size that will fit the layout:

Popover using a fitting size

Note that this also works if we embed our content view controller in a navigation controller:

Popover with navigation bar

The navigation controller adjusts its preferred content size to take into account the size of the navigation bar.

Popover Guidelines

This technique works well when you know the content size will fit within the typical popover size (300-400 points wide). Once you start to exceed 600 points wide you run the risk the popover will not fit and the system will shrink the content anyway.

The iOS Human Interface Guidelines warn against making the popover too large:

Avoid making a popover too big. A popover shouldn’t take over the entire screen. Make it only big enough to display its contents and point to the place it came from. Be aware that the system might adjust the size of a popover to ensure it fits well onscreen.

Read More