[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.’

right?
After this, add getter/setter for

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]UIPopoverController *popoverController;
[…]
@property(nonatomic, retain) UIPopoverController *popoverController;[/code]

Add this code in your button action:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- (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
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

[popoverView release];
[popoverContent release];
[cccp release];
}[/code]

…and finally close the UIPopoverController on touch:

[code lang=”java” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]- (void) closePopover {
[self.popoverController dismissPopoverAnimated:YES];
}[/code]

it’s all!
Easy as ever!

Rif: albertopasca.it

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.