Class

UIViewController

The UIViewController class provides the infrastructure for managing the views of your iOS apps. A view controller manages a set of views that make up a portion of your app’s user interface. It is responsible for loading and disposing of those views, for managing interactions with those views, and for coordinating responses with any appropriate data objects. View controllers also coordinate their efforts with other controller objects—including other view controllers—and help manage your app’s overall interface.

Overview

You rarely create instances of the UIViewController class directly. Instead, you create instances of UIViewController subclasses and use those objects to provide the specific behaviors and visual appearances that you need.

A view controller’s main responsibilities include the following:

  • Updating the contents of the views, usually in response to changes to the underlying data.

  • Responding to user interactions with views.

  • Resizing views and managing the layout of the overall interface.

A view controller is tightly bound to the views it manages and takes part in the responder chain used to handle events. View controllers are also UIResponder objects and are inserted into the responder chain between the view controller’s root view and that view’s superview, which typically belongs to a different view controller. If none of the view controller’s views handle an event, the view controller has the option of handling the event or passing it along to the superview.

View controllers are rarely used in isolation. Instead, you often use multiple view controllers, each of which owns a portion of your app’s user interface. For example, one view controller might display a table of items while a different view controller displays the selected item from that table. Usually, only the views from one view controller are visible at a time. A view controller may present a different view controller to display a new set of views, or it may act as a container for other view controllers’ content and animate views however it wants.

Subclassing Notes

Every app contains at least one custom subclass of UIViewController. More often, apps contain many custom view controllers. Custom view controllers define the overall behaviors of your app, including the app’s appearance and how it responds to user interactions. The following sections provide a brief overview of some of the tasks your custom subclass performs. For detailed information about using and implementing view controllers, see View Controller Programming Guide for iOS.

View Management

Each view controller manages a view hierarchy, the root view of which is stored in the view property of this class. The root view acts primarily as a container for the rest of the view hierarchy. The size and position of the root view is determined by the object that owns it, which is either a parent view controller or the app’s window. The view controller that is owned by the window is the app’s root view controller and its view is sized to fill the window.

View controllers load their views lazily. Accessing the view property for the first time loads or creates the view controller’s views. There are several ways to specify the views for a view controller:

  • Specify the view controller and its views in your app’s Storyboard. Storyboards are the preferred way to specify your views. With a storyboard, you specify the views and their connections to the view controller. You also specify the relationships and segues between your view controllers, which makes it easier to see and modify your app'€™s behavior.

    To load a view controller from a storyboard, call the instantiateViewController(withIdentifier:) method of the appropriate UIStoryboard object. The storyboard object creates the view controller and returns it to your code.

  • Specify the views for a view controller using a Nib file. A nib file lets you specify the views of a single view controller but does not let you define segues or relationships between view controllers. The nib file also stores only minimal information about the view controller itself.

    To initialize a view controller object using a nib file, create your view controller class programmatically and initialize it using the init(nibName:bundle:) method. When its views are requested, the view controller loads them from the nib file.

  • Specify the views for a view controller using the loadView() method. In that method, create your view hierarchy programmatically and assign the root view of that hierarchy to the view controller’s view property.

All of these techniques have the same end result, which is to create the appropriate set of views and expose them through the view property.

A view controller’s root view is always sized to fit its assigned space. For other views in your view hierarchy, use Interface Builder to specify the Auto Layout constraints that govern how each view is positioned and sized within its superview’s bounds. You can also create constraints programmatically and add them to your views at appropriate times. For more information about how to create constraints, see Auto Layout Guide.

Handling View-Related Notifications

When the visibility of its views changes, a view controller automatically calls its own methods so that subclasses can respond to the change. Use a method like viewWillAppear(_:) to prepare your views to appear onscreen, and use the viewWillDisappear(_:) to save changes or other state information. Use other methods to make appropriate changes.

Figure 1 shows the possible visible states for a view controller’s views and the state transitions that can occur. Not all ‘will’ callback methods are paired with only a ‘did’ callback method. You need to ensure that if you start a process in a ‘will’ callback method, you end the process in both the corresponding ‘did’ and the opposite ‘will’ callback method.

Figure 1

Valid State Transitions

Handling View Rotations

As of iOS 8, all rotation-related methods are deprecated. Instead, rotations are treated as a change in the size of the view controller’s view and are therefore reported using the viewWillTransition(to:with:) method. When the interface orientation changes, UIKit calls this method on the window’s root view controller. That view controller then notifies its child view controllers, propagating the message throughout the view controller hierarchy.

In iOS 6 and iOS 7, your app supports the interface orientations defined in your app’s Info.plist file. A view controller can override the supportedInterfaceOrientations method to limit the list of supported orientations. Typically, the system calls this method only on the root view controller of the window or a view controller presented to fill the entire screen; child view controllers use the portion of the window provided for them by their parent view controller and no longer participate directly in decisions about what rotations are supported. The intersection of the app'€™s orientation mask and the view controller'€™s orientation mask is used to determine which orientations a view controller can be rotated into.

You can override the preferredInterfaceOrientationForPresentation for a view controller that is intended to be presented full screen in a specific orientation.

When a rotation occurs for a visible view controller, the willRotate(to:duration:), willAnimateRotation(to:duration:), and didRotate(from:) methods are called during the rotation. The viewWillLayoutSubviews() method is also called after the view is resized and positioned by its parent. If a view controller is not visible when an orientation change occurs, then the rotation methods are never called. However, the viewWillLayoutSubviews() method is called when the view becomes visible. Your implementation of this method can call the statusBarOrientation method to determine the device orientation.

Implementing a Container View Controller

A custom UIViewController subclass can also act as a container view controller. A container view controller manages the presentation of content of other view controllers it owns, also known as its child view controllers. A child'€™s view can be presented as-is or in conjunction with views owned by the container view controller.

Your container view controller subclass should declare a public interface to associate its children. The nature of these methods is up to you and depends on the semantics of the container you are creating. You need to decide how many children can be displayed by your view controller at once, when those children are displayed, and where they appear in your view controller'€™s view hierarchy. Your view controller class defines what relationships, if any, are shared by the children. By establishing a clean public interface for your container, you ensure that children use its capabilities logically, without accessing too many private details about how your container implements the behavior.

Your container view controller must associate a child view controller with itself before adding the child'€™s root view to the view hierarchy. This allows iOS to properly route events to child view controllers and the views those controllers manage. Likewise, after it removes a child'€™s root view from its view hierarchy, it should disconnect that child view controller from itself. To make or break these associations, your container calls specific methods defined by the base class. These methods are not intended to be called by clients of your container class; they are to be used only by your container'€™s implementation to provide the expected containment behavior.

Here are the essential methods you might need to call:

Memory Management

Memory is a critical resource in iOS, and view controllers provide built-in support for reducing their memory footprint at critical times. The UIViewController class provides some automatic handling of low-memory conditions through its didReceiveMemoryWarning() method, which releases unneeded memory.

State Preservation and Restoration

If you assign a value to the view controller'€™s restorationIdentifier property, the system may ask the view controller to encode itself when the app transitions to the background. When preserved, a view controller preserves the state of any views in its view hierarchy that also have restoration identifiers. View controllers do not automatically save any other state. If you are implementing a custom container view controller, you must encode any child view controllers yourself. Each child you encode must have a unique restoration identifier.

For more information about how the system determines which view controllers to preserve and restore, see App Programming Guide for iOS.

Symbols

Configuring a View Controller Using Nib Files

init(nibName: String?, bundle: Bundle?)

Returns a newly initialized view controller with the nib file in the specified bundle.

var nibName: String?

The name of the view controller'€™s nib file, if one was specified.

var nibBundle: Bundle?

The view controller'€™s nib bundle if it exists.

Interacting with Storyboards and Segues

var storyboard: UIStoryboard?

The storyboard from which the view controller originated.

func shouldPerformSegue(withIdentifier: String, sender: Any?)

Determines whether the segue with the specified identifier should be performed.

func prepare(for: UIStoryboardSegue, sender: Any?)

Notifies the view controller that a segue is about to be performed.

func performSegue(withIdentifier: String, sender: Any?)

Initiates the segue with the specified identifier from the current view controller'€™s storyboard file.

func allowedChildViewControllersForUnwinding(from: UIStoryboardUnwindSegueSource)

Returns an array of child view controllers that should be searched for an unwind segue destination.

func childViewControllerContaining(UIStoryboardUnwindSegueSource)

Returns the child view controller that contains the source of the unwind segue.

func canPerformUnwindSegueAction(Selector, from: UIViewController, withSender: Any)

Called on a view controller to determine whether it wants to respond to an unwind action.

func unwind(for: UIStoryboardSegue, towardsViewController: UIViewController)

Called when an unwind segue transitions to a new view controller.

func forUnwindSegueAction(Selector, from: UIViewController, withSender: Any?)

Called when an unwind segue action wants to search a container'€™s children for a view controller to handle the unwind action.

Deprecated
func segueForUnwinding(to: UIViewController, from: UIViewController, identifier: String?)

Called when an unwind segue action needs to transition between two view controllers.

Deprecated

Managing the View

var view: UIView!

The view that the controller manages.

func loadView()

Creates the view that the controller manages.

func viewDidLoad()

Called after the controller'€™s view is loaded into memory.

func loadViewIfNeeded()

Loads the view controller’s view if it has not yet been loaded.

var viewIfLoaded: UIView?

The view controller’s view, or nil if the view is not yet loaded.

var title: String?

A localized string that represents the view this controller manages.

var preferredContentSize: CGSize

The preferred size for the view controller’s view.

Presenting View Controllers

var modalPresentationStyle: UIModalPresentationStyle

The presentation style for modally presented view controllers.

var modalTransitionStyle: UIModalTransitionStyle

The transition style to use when presenting the view controller.

var isModalInPopover: Bool

A Boolean value indicating whether the view controller should be presented modally by a popover.

func show(UIViewController, sender: Any?)

Presents a view controller in a primary context.

func showDetailViewController(UIViewController, sender: Any?)

Presents a view controller in a secondary (or detail)€ context.

func dismiss(animated: Bool, completion: (() -> Void)? = nil)

Dismisses the view controller that was presented modally by the view controller.

var definesPresentationContext: Bool

A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.

var providesPresentationContextTransitionStyle: Bool

A Boolean value that indicates whether the view controller specifies the transition style for view controllers it presents.

var disablesAutomaticKeyboardDismissal: Bool

Returns a Boolean indicating whether the current input view is dismissed automatically when changing controls.

Supporting Custom Transitions and Presentations

var transitioningDelegate: UIViewControllerTransitioningDelegate?

The delegate object that provides transition animator, interactive controller, and custom presentation controller objects.

var transitionCoordinator: UIViewControllerTransitionCoordinator?

Returns the active transition coordinator object.

func targetViewController(forAction: Selector, sender: Any?)

Returns the view controller that responds to the action.

var presentationController: UIPresentationController?

The nearest presentation controller that is managing the current view controller.

var popoverPresentationController: UIPopoverPresentationController?

The nearest popover presentation controller that is managing the current view controller.

Responding to View Events

func viewWillAppear(Bool)

Notifies the view controller that its view is about to be added to a view hierarchy.

func viewDidAppear(Bool)

Notifies the view controller that its view was added to a view hierarchy.

func viewWillDisappear(Bool)

Notifies the view controller that its view is about to be removed from a view hierarchy.

func viewDidDisappear(Bool)

Notifies the view controller that its view was removed from a view hierarchy.

Configuring the View’s Layout Behavior

func viewWillLayoutSubviews()

Called to notify the view controller that its view is about to layout its subviews.

func viewDidLayoutSubviews()

Called to notify the view controller that its view has just laid out its subviews.

func updateViewConstraints()

Called when the view controller'€™s view needs to update its constraints.

var bottomLayoutGuide: UILayoutSupport

Indicates the lowest vertical extent for your onscreen content, for use with Auto Layout constraints.

var topLayoutGuide: UILayoutSupport

Indicates the highest vertical extent for your onscreen content, for use with Auto Layout constraints.

var edgesForExtendedLayout: UIRectEdge

The extended edges to use for the layout.

var extendedLayoutIncludesOpaqueBars: Bool

A Boolean value indicating whether or not the extended layout includes opaque bars.

var automaticallyAdjustsScrollViewInsets: Bool

A Boolean value that indicates whether the view controller should automatically adjust its scroll view insets.

Configuring the View Rotation Settings

var shouldAutorotate: Bool

Returns a Boolean value indicating whether the view controller'€™s contents should auto rotate.

var supportedInterfaceOrientations: UIInterfaceOrientationMask

Returns all of the interface orientations that the view controller supports.

var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation

Returns the interface orientation to use when presenting the view controller.

class func attemptRotationToDeviceOrientation()

Attempts to rotate all windows to the orientation of the device.

Adapting to Environment Changes

func collapseSecondaryViewController(UIViewController, for: UISplitViewController)

Called when a split view controller transitions to a compact-width size class.

func separateSecondaryViewController(for: UISplitViewController)

Called when a split view controller transitions to a regular-width size class.

Managing Child View Controllers in a Custom Container

var childViewControllers: [UIViewController]

An array of view controllers that are children of the current view controller.

func addChildViewController(UIViewController)

Adds the specified view controller as a child of the current view controller.

func removeFromParentViewController()

Removes the view controller from its parent.

var shouldAutomaticallyForwardAppearanceMethods: Bool

Returns a Boolean value indicating whether appearance methods are forwarded to child view controllers.

func beginAppearanceTransition(Bool, animated: Bool)

Tells a child controller its appearance is about to change.

func endAppearanceTransition()

Tells a child controller its appearance has changed.

func setOverrideTraitCollection(UITraitCollection?, forChildViewController: UIViewController)

Changes the traits assigned to the specified child view controller.

func overrideTraitCollection(forChildViewController: UIViewController)

Retrieves the trait collection for a child view controller.

Responding to Containment Events

func willMove(toParentViewController: UIViewController?)

Called just before the view controller is added or removed from a container view controller.

func didMove(toParentViewController: UIViewController?)

Called after the view controller is added or removed from a container view controller.

Getting Other Related View Controllers

var presentingViewController: UIViewController?

The view controller that presented this view controller.

var presentedViewController: UIViewController?

The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy.

var parent: UIViewController?

The parent view controller of the recipient.

var navigationController: UINavigationController?

The nearest ancestor in the view controller hierarchy that is a navigation controller.

var splitViewController: UISplitViewController?

The nearest ancestor in the view controller hierarchy that is a split view controller.

var tabBarController: UITabBarController?

The nearest ancestor in the view controller hierarchy that is a tab bar controller.

Handling Memory Warnings

func didReceiveMemoryWarning()

Sent to the view controller when the app receives a memory warning.

Managing State Restoration

var restorationIdentifier: String?

The identifier that determines whether the view controller supports state restoration.

var restorationClass: UIViewControllerRestoration.Type?

The class responsible for recreating this view controller when restoring the app'€™s state.

func encodeRestorableState(with: NSCoder)

Encodes state-related information for the view controller.

func decodeRestorableState(with: NSCoder)

Decodes and restores state-related information for the view controller.

func applicationFinishedRestoringState()

Called on restored view controllers after other object decoding is complete.

Supporting App Extensions

var extensionContext: NSExtensionContext?

Returns the extension context of the view controller.

Working With 3D Touch Previews and Preview Quick Actions

The methods in this task group are available on devices that support 3D Touch. The end-user terminology for the views presented during the phases of force-based touches includes peek and pop. For clarity here, and to align with the API names, this document uses the corresponding terms preview and commit view. To learn more about 3D Touch, read Adopting 3D Touch on iPhone.

func registerForPreviewing(with: UIViewControllerPreviewingDelegate, sourceView: UIView)

Registers a view controller to participate with 3D Touch preview (peek) and commit (pop).

func unregisterForPreviewing(withContext: UIViewControllerPreviewing)

Unregisters a previously registered view controller identified by its context object.

var previewActionItems: [UIPreviewActionItem]

The quick actions displayed when a user swipes upward on a 3D Touch preview.

Managing the Status Bar

var childViewControllerForStatusBarHidden: UIViewController?

Called when the system needs the view controller to use for determining status bar hidden/unhidden state.

var childViewControllerForStatusBarStyle: UIViewController?

Called when the system needs the view controller to use for determining status bar style.

var preferredStatusBarStyle: UIStatusBarStyle

The preferred status bar style for the view controller.

var prefersStatusBarHidden: Bool

Specifies whether the view controller prefers the status bar to be hidden or shown.

var modalPresentationCapturesStatusBarAppearance: Bool

Specifies whether a view controller, presented non-fullscreen, takes over control of status bar appearance from the presenting view controller.

var preferredStatusBarUpdateAnimation: UIStatusBarAnimation

Specifies the animation style to use for hiding and showing the status bar for the view controller.

func setNeedsStatusBarAppearanceUpdate()

Indicates to the system that the view controller status bar attributes have changed.

Configuring a Navigation Interface

var navigationItem: UINavigationItem

The navigation item used to represent the view controller in a parent'€™s navigation bar.

var hidesBottomBarWhenPushed: Bool

A Boolean value indicating whether the toolbar at the bottom of the screen is hidden when the view controller is pushed on to a navigation controller.

func setToolbarItems([UIBarButtonItem]?, animated: Bool)

Sets the toolbar items to be displayed along with the view controller.

var toolbarItems: [UIBarButtonItem]?

The toolbar items associated with the view controller.

Configuring Tab Bar Items

var tabBarItem: UITabBarItem!

The tab bar item that represents the view controller when added to a tab bar controller.

Adding Editing Behaviors to Your View Controller

var isEditing: Bool

A Boolean value indicating whether the view controller currently allows the user to edit the view contents.

func setEditing(Bool, animated: Bool)

Sets whether the view controller shows an editable view.

var editButtonItem: UIBarButtonItem

Returns a bar button item that toggles its title and associated state between Edit and Done.

Accessing the Available Key Commands

func addKeyCommand(UIKeyCommand)

Associates the specified keyboard shortcut with the view controller.

func removeKeyCommand(UIKeyCommand)

Removes the key command from the view controller.

Managing Banner Ads

var canDisplayBannerAds: Bool

A boolean value that indicates whether the view controller is configured to display banner ads.

Deprecated
var originalContentView: UIView!

The originally configured content view of the view controller before banner ads were enabled.

Deprecated

Determining Whether the View Controller is Displaying an Ad

var isPresentingFullScreenAd: Bool

A boolean value that indicates whether the view controller is displaying a full-screen ad.

Deprecated
var isDisplayingBannerAd: Bool

A boolean value that indicates whether the view controller is displaying a banner ad.

Deprecated

Managing Interstitial Ads

class func prepareInterstitialAds()

Prepares the iAd framework to display interstitial ads, which may involve prefetching ad assets.

Deprecated
var interstitialPresentationPolicy: ADInterstitialPresentationPolicy

Determines whether interstitials should be presented at all and whether the framework or app should manage the presentation.

Deprecated
func requestInterstitialAdPresentation()

Asks the framework to display an interstitial ad.

Deprecated
var shouldPresentInterstitialAd: Bool

Returns whether an interstitial ad should be displayed.

Deprecated

Deprecated

func rotatingHeaderView()

Returns the header view to transition during an interface orientation change.

Deprecated
func rotatingFooterView()

Returns the footer view to transition during an interface orientation change.

Deprecated
var interfaceOrientation: UIInterfaceOrientation

Convenience property that provides the current orientation of the interface, meaningful only if the view controller is taking up the full screen.

Deprecated
func willRotate(to: UIInterfaceOrientation, duration: TimeInterval)

Sent to the view controller just before the user interface begins rotating.

Deprecated
func willAnimateRotation(to: UIInterfaceOrientation, duration: TimeInterval)

Sent to the view controller before performing a one-step user interface rotation.

Deprecated
func didRotate(from: UIInterfaceOrientation)

Sent to the view controller after the user interface rotates.

Deprecated
var searchDisplayController: UISearchDisplayController?

The search display controller associated with the view controller.

Deprecated
func shouldAutomaticallyForwardRotationMethods()

Returns a Boolean value indicating whether rotation methods are forwarded to child view controllers.

Deprecated
func presentMoviePlayerViewControllerAnimated(MPMoviePlayerViewController!)

Presents the movie player view controller using the standard movie player transition.

Deprecated
func dismissMoviePlayerViewControllerAnimated()

Dismisses a movie player view controller using the standard movie player transition.

Deprecated

Constants

UIModalPresentationStyle

Modal presentation styles available when presenting view controllers.

UIModalTransitionStyle

Transition styles available when presenting view controllers.

ADInterstitialPresentationPolicy

Policy options governing how and when interstitial ads may be presented from a view controller.

Deprecated
Exceptions

Exceptions raised by view controllers.

Notifications

static let UIViewControllerShowDetailTargetDidChange: NSNotification.Name

Posted when a split view controller is expanded or collapsed.

Instance Properties

var isBeingDismissed: Boolvar isBeingPresented: Boolvar isMovingFromParentViewController: Boolvar isMovingToParentViewController: Bool
var restoresFocusAfterTransition: Bool

A Boolean value that indicates whether an item that previously was focused should again become focused when the item's view controller becomes visible and focusable.

var isViewLoaded: Bool