Vad
Vad

Reputation: 3740

Storyboard - Open UIViewController as UIPopoverController

For my iPad version of the app I want to open my UIViewController as a UIPopoverController from the click of a button. So, the real code for view controller opening is below. How can I easily convert such code into opening a UIViewController as a UIPopoverController?

Code:

UIStoryboard *sb = [UIStoryboard storyboardWithName:[[NSBundle mainBundle].infoDictionary        objectForKey:@"UIMainStoryboardFile"] bundle:[NSBundle mainBundle]];

UIViewController *aboutView = [sb instantiateViewControllerWithIdentifier:@"AboutViewController"];
aboutView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:aboutView animated:YES completion:NULL];

Upvotes: 0

Views: 512

Answers (2)

matt
matt

Reputation: 534914

A common solution is to have two storyboards, one for iPhone, one for iPad. That way you can use the popover segue in the iPad storyboard and the modal segue in the iPhone storyboard. You can readily arrange your Info.plist so that the correct storyboard loads automatically at launch time. You will still need some conditional code, though, since your code will respond differently to having a presented view controller than having a popover.

Upvotes: 1

Martin Koles
Martin Koles

Reputation: 5247

Use something like:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    UIPopoverController *poc = [[UIPopoverController alloc] initWithContentViewController:aboutView];
    [poc presentPopoverFromRect:CGRectMake(somePoint.x, somePointY, 1.0, 1.0) inView:self.view permittedArrowDirections: UIPopoverArrowDirectionAny animated:YES];
} else {
    aboutView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:aboutView animated:YES completion:NULL];
}

You can also present the popover from a button and you also can control the direction in which the popover will be presented. If you use UIPopoverArrowDirectionAny, iOS will make a smart decision for the popover to be visible.

You should also keep a strong reference to your popover and only present it while it is nil to make sure the popover is only present once. That means if the popover is dismissed, set the property holding it to nil.

Upvotes: 3

Related Questions