Apple is missing documentation on how to use UIPopoverBackgroundView
class introduced in iOS5. Anyone have an example?
I have tried to subclass it, but my XCode 4.2 on Lion is missing UIPopoverBackgroundView.h
Edit: Unsurprisingly, it should have been imported as #import <UIKit/UIPopoverBackgroundView.h>
Another link only answer, but customising UIPopoverBackgroundView
is more work than you might realise given the limited documentation available and this github project has a complete working example which saved me a lot of time: https://github.com/GiK/GIKPopoverBackgroundView
It's fairly straightforward to drop into your own project. The most fiddly part is adapting the cap insets for whatever custom images you're using. I'd recommend doing your customisations in-situ in the project and as it's easy to verify all the popover orientation/direction use cases display correctly in the simulator before migrating it into your own project.
To add to the other, link-only answers, here is how this is done.
Declare the following in your interface:
+(UIEdgeInsets)contentViewInsets;
+(CGFloat)arrowHeight;
+(CGFloat)arrowBase;
@property(nonatomic,readwrite) CGFloat arrowOffset;
@property(nonatomic,readwrite) UIPopoverArrowDirection arrowDirection;
The class methods are straightforward: contentViewInsets
returns the width of your borders all the way round (not including the arrow), arrowHeight
is the height of your arrow, arrowBase
is the base of your arrow.
[self setNeedsLayout]
. layoutSubviews
. In here, according to the arrowDirection
and arrowOffset
properties, you have to adjust the frames of your background view and arrow view.
self.bounds
, inset by arrowHeight
on whatever edge the arrow is onarrowOffset
away from the centre of self
(correct according to the axis). You have to change the image orientation if the arrow direction is not up, but my popover would only be up so I didn't do that.Here is the layoutSubviews
method for my Up-only subclass:
-(void)layoutSubviews
{
if (self.arrowDirection == UIPopoverArrowDirectionUp)
{
CGFloat height = [[self class] arrowHeight];
CGFloat base = [[self class] arrowBase];
self.background.frame = CGRectMake(0, height, self.frame.size.width, self.frame.size.height - height);
self.arrow.frame = CGRectMake(self.frame.size.width * 0.5 + self.arrowOffset - base * 0.5, 1.0, base, height);
[self bringSubviewToFront:self.arrow];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With