Display Popovers on the iPad

The PopoverController class, available exclusively for the iPad, is a nice way to present information to the user. The popover content is layered on top of your existing content in a special type of window. In this tutorial, we’ll show a popover containing a table view when the user touches a button.

Open Xcode and create a new Single View Application. For product name, use PopoverDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPad is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag a Button to the main View. The main View should look like this.

In ViewController.m in the interface section declare the following properties.

@interface ViewController ()

- (IBAction)showPopover:(UIButton *)sender;


Go back to ViewController.xib. Select the Assistant Editor. On the right side select ViewController.m. Ctrl-click and drag from the button to the showPopover method in ViewController.m.

Also, declare the following property in the interface section

@property (nonatomic,strong) UIPopoverController *popOver;

We will use the popOver property in the showPopover method. First we will create a new table viewcontroller. Add a new File -> iOS -> Cocoa Touch -> Objective-C class and make it a subclass of UITableViewController. Select the "With XIB for user interface" checkbox and name the class PopoverViewController. Go to PopoverViewController.m and change the following methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
return 1;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
return 10;

Add the following line after the Configure the method comment in the tableView:cellForRowAtIndexPath method

// Configure the cell...
cell.textLabel.text=[NSString stringWithFormat:@"Row number %d",indexPath.row];

We fill our table view with 10 rows with some text containing the row number. Go back to ViewController.m and implement the showPopover method


- (IBAction)showPopover:(UIButton *)sender 
PopoverViewController *PopoverView =[[PopoverViewController alloc] initWithNibName:@"PopoverViewController" bundle:nil];
self.popOver =[[UIPopoverController alloc] initWithContentViewController:PopoverView];
[self.popOver presentPopoverFromRect:sender.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];

We initialize our created view controller and load it in our popover property. The permitted arrow direction is down which means the popover will show up above our button.

Build and Run, and click the button to display the popover.

Rotate the device to portrait view.

You can download the source code of the PopoverDemo at the ioscreator repository on github.