Simplified popovers

In this post, I’ll present a microclass that can give you simplified popover (

UIPopoverController

) handling in many cases, including automatic rotation updates. Links to code below.

What PopoverHelper does

Normally, this is how you need to work with a popover:

  1. Set up the content view controller that will appear in the popover.
  2. Alloc and init the popover.
  3. Often, you need to resize the popover content.
  4. Gather information about where and how the popover will be presented.
  5. Present the popover.
  6. Track orientation changes, and update the popover’s position accordingly.
  7. Dismiss the popover according to UI actions, often using a popover delegate.
  8. Release the popover controller.

In my use so far, I’ve found that I’m repeating myself when it comes to many of these steps.  So, like any decent coder, I feel the compelling urge to refactor.  The result is

PopoverHelper

, a compact class that can turn the above steps into code like this:

MyViewController *myController = [MyViewController beInit];
UIPopoverController *popover =  [PopoverHelper popoverForViewController:myController];
[popover presentPopoverFromView:myView];

Behind the scenes, it sets up the popover object as an autonomous object with a delegate that releases it upon dismissal, sets the content size to match that of

myController

, and presents the popover from

myView

‘s frame within its superview.  It also listens for device orientation changes, and re-presents your popover for you from the same source view, or dismisses the popover if the source view becomes hidden.  You can programmatically dismiss the popover with a call to

[myPopover dismissAndRelease]

, but you never have to explicitly worry about its memory management unless you take over the delegate.

How it works

The code is simple and speaks for itself (links to actual files below).  Here’s the header:

In the m file, you can see that PopoverHelper works by setting the delegate for you to its own handler, and tracks the source view and last device orientation.  When a rotation occurs, it re-presents the popover for you.  When the popover is discarded, it cleans up and is ready to give you a new popover.

Source and References

The beInit method is explained in an earlier post.

PopoverHelper.h

PopoverHelper.m

8 Comments