Sunday, November 1, 2015

iOS Tutorial - Part 35 - Popover for iPhone and iPad

Create Popover for iPhone and iPad


Video Description 
Sometimes we don't want to cover the whole view for showing another view controller. This is mostly for iPad because it has larger screen. But it's also possible to show popover on iPhone. Creating a popover is very easy, it's a type of connection between view controllers. All you have to do is to connect the button or whatever action you want to another view controller by control dragging and the choose "Present As Popover", that's it. This will show popover only for iPad but for iPhone you have to do one more step.

Popover for iPhone

iOS 8 offered an easy way to implement popover for iPhone. All you have to do is to declare UIPopoverPresentationControllerDelegate:
@interface ViewController () <UIPopoverPresentationControllerDelegate>

Then put the view controller delegate equal to self:
self.popoverTvc.popoverPresentationController.delegate = self;

And at the end implement the delegate method:
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

Adapt the popover size based on the content

The popover that we created so far has not a proper size. The default size is very big and unnecessary. In order to fix this issue we need to override the prefferedContentSize property of the popover view controller. In this example we have a table view and we need to get the size of the table view and show only the cells that has value (not empty cells).
if (self.tableView && self.presentingViewController) {
        self.preferredContentSize = [self.tableView sizeThatFits:self.presentingViewController.view.bounds.size];
    }
First we chech if tableView and presentingViewController (The view controller that is presenting at that moment) is not nill. then we set the preferredContentSize equal the tableiew size that fits presentingViewController size.

Download

Download this app here