Display PopOver iOS Tutorial

A popover is a transient view that appears above other content onscreen when you tap a control or in an area. Typically, a popover includes an arrow pointing to the location from which it emerged. In this tutorial a popover is displayed containing a text view. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSPopoverTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and select the View Controller. Go to the Editor menu and select Embed In -> Naviagation Controller. Drag a Bar Button Item to the right side of the Navigation Bar. Select the Bar Button Item and go to the Attributes Inspector. In the Bar Button Item section Change the System Item to Action.

Next, Drag a new View Controller from the Object Library on to the Storyboard. Drag a Text View from the Object Library at the top of this View Controller. This View Controller will be displayed in the popover.

Add a new file to the project, Select File -> New ->File and then select iOS -> Source -> Cocoa Touch Class. Name it PopoverViewController and make it a subclass of UIViewController.

Go back to Main.storyboard and select the added View Controller. Go to the Identity inspector and in the Custom Class section change the class to PopoverViewController.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Action Bar Button Item to the ViewController class and create the following Action

Go to the ViewController.swift file and Implement the displayPopover(_:) action method

@IBAction func displayPopover(_ sender: UIBarButtonItem) {
    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "PopoverViewController")
    vc.modalPresentationStyle = .popover
    let popover: UIPopoverPresentationController = vc.popoverPresentationController!
    popover.barButtonItem = sender
    present(vc, animated: true, completion:nil)

The UIPopoverPresentationController manages the presentation behaviour. Here the PopOverViewController is instantiated from the Storyboard and displayed. The barButtonItem property is set to point the arrow to the Action Bar Button Item.

Build and Run the project and press the Action button,. The popvover will be displayed. It can be dismissed by clicking outside the popover.

You can download the source code of the IOSPopoverTutorial at the ioscreator repository on Github.