[Objective-C] Ipad popover controller

Hi all,
today a snippet to open in a view a popover controller. It’s the view with the arrow (do you know?)

Like this, take a look here:

Ipad Popover
First of all, check if you device is an Ipad! It’s very important… else the result will be this:

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason:
‘-[UIPopoverController initWithContentViewController:] called when not running under UIUserInterfaceIdiomPad.’

After this, add getter/setter for

UIPopoverController *popoverController;
@property(nonatomic, retain) UIPopoverController *popoverController;

Add this code in your button action:

- (IBAction) yourAction {
  UIViewController* popoverContent = [[UIViewController alloc] init];
  UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 150)];
  popoverView.backgroundColor = [UIColor whiteColor];
  popoverContent.modalInPopover = YES;
  popoverContent.modalPresentationStyle = UIModalPresentationFormSheet;

  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [button setFrame:CGRectMake(20, 20, 160, 30)];
  [button setTitle:@"Close" forState:UIControlStateNormal];
  [button addTarget:self action:@selector(closePopover) forControlEvents:UIControlEventTouchUpInside];
  [popoverView addSubview:button];

  UITextView *cccp = [[UITextView alloc] initWithFrame:CGRectMake(10, 50, 180, 120)];
  cccp.userInteractionEnabled = NO;
  [cccp setText:@"Write your text here\n\nwww.albertopasca.it"];
  cccp.textAlignment = UITextAlignmentCenter;

  [popoverView addSubview:cccp];
  popoverContent.view = popoverView;
  popoverContent.contentSizeForViewInPopover = CGSizeMake(200, 150);

  self.popoverController =
    [[[UIPopoverController alloc] initWithContentViewController:popoverContent] autorelease];
  [self.popoverController presentPopoverFromRect:copy.frame
    permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

  [popoverView release];
  [popoverContent release];
  [cccp release];

…and finally close the UIPopoverController on touch:

- (void) closePopover {
  [self.popoverController dismissPopoverAnimated:YES];

it’s all!
Easy as ever!

Rif: albertopasca.it