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.
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 file. 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
instantiateViewControllerWithIdentifier:method of the appropriateUIStoryboardobject. 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
initWithNibName: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
loadViewmethod. In that method, create your view hierarchy programmatically and assign the root view of that hierarchy to the view controller’sviewproperty.
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.
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 viewWillTransitionToSize:withTransitionCoordinator: 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 willRotateToInterfaceOrientation:duration:, willAnimateRotationToInterfaceOrientation:duration:, and didRotateFromInterfaceOrientation: 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.
-
init(nibName:bundle:) - initWithNibName:bundle:Designated InitializerReturns a newly initialized view controller with the nib file in the specified bundle.
Declaration
Parameters
nibNameThe name of the nib file to associate with the view controller. The nib file name should not contain any leading path information. If you specify
nil, thenibNameproperty is set tonil.nibBundleThe bundle in which to search for the nib file. This method looks for the nib file in the bundle's language-specific project directories first, followed by the
Resourcesdirectory. If this parameter isnil, the method uses the heuristics described below to locate the nib file.Return Value
A newly initialized
UIViewControllerobject.Discussion
This is the designated initializer for this class. When using a storyboard to define your view controller and its associated views, you never initialize your view controller class directly. Instead, view controllers are instantiated by the storyboard either automatically when a segue is triggered or programmatically when your app calls the
instantiateViewControllerWithIdentifier:method of a storyboard object. When instantiating a view controller from a storyboard, iOS initializes the new view controller by calling itsinitWithCoder:method instead of this method and sets thenibNameproperty to a nib file stored inside the storyboard.The nib file you specify is not loaded right away. It is loaded the first time the view controller's view is accessed. If you want to perform additional initialization after the nib file is loaded, override the
viewDidLoadmethod and perform your tasks there.If you specify
nilfor thenibNameparameter and you do not override theloadViewmethod, the view controller searches for a nib file as described in thenibNameproperty.For more information about how a view controller loads its view, see Resource Management in View Controllers.
Availability
Available in iOS 2.0 and later.
See Also
-
The name of the view controller's nib file, if one was specified. (read-only)
Declaration
Swift
var nibName: String? { get }Objective-C
@property(nonatomic, readonly, copy) NSString *nibNameDiscussion
This property contains the value specified at initialization time to the
initWithNibName:bundle:method. The value of this property may benil.If you use a nib file to store your view controller's view, it is recommended that you specify that nib file explicitly when initializing your view controller. However, if you do not specify a nib name, and do not override the
loadViewmethod in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the.nibextension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:If the view controller class name ends with the word ‘Controller’, as in
MyViewController, it looks for a nib file whose name matches the class name without the word ‘Controller’, as inMyView.nib.It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is
MyViewController, it looks for aMyViewController.nibfile.
Availability
Available in iOS 2.0 and later.
See Also
-
storyboard storyboardPropertyThe storyboard from which the view controller originated. (read-only)
Declaration
Swift
var storyboard: UIStoryboard? { get }Objective-C
@property(nonatomic, readonly, strong) UIStoryboard *storyboardDiscussion
If the view controller was not instantiated from a storyboard, this property is
nil.Availability
Available in iOS 5.0 and later.
-
Determines whether the segue with the specified identifier should be performed.
Declaration
Swift
func shouldPerformSegueWithIdentifier(_identifier: String, sendersender: AnyObject?) -> BoolObjective-C
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifiersender:(id)senderParameters
identifierThe string that identifies the triggered segue. In Interface Builder, you specify the segue’s identifier string in the attributes inspector. This string is used only for locating the segue inside the storyboard.
senderThe object that initiated the segue. This object is made available for informational purposes during the actual segue.
Return Value
YEStrueif the segue should be performed orNOfalseif it should be ignored.Discussion
Subclasses can override this method and use it to perform segues conditionally based on current conditions. If you do not implement this method, all segues are performed.
Availability
Available in iOS 6.0 and later.
-
Notifies the view controller that a segue is about to be performed.
Declaration
Swift
func prepareForSegue(_segue: UIStoryboardSegue, sendersender: AnyObject?)Objective-C
- (void)prepareForSegue:(UIStoryboardSegue *)seguesender:(id)senderParameters
segueThe segue object containing information about the view controllers involved in the segue.
senderThe object that initiated the segue. You might use this parameter to perform different actions based on which control (or other object) initiated the segue.
Discussion
The default implementation of this method does nothing. Subclasses override this method and use it to configure the new view controller prior to it being displayed. The segue object contains information about the transition, including references to both view controllers that are involved.
Because segues can be triggered from multiple sources, you can use the information in the
segueandsenderparameters to disambiguate between different logical paths in your app. For example, if the segue originated from a table view, the sender parameter would identify the table view cell that the user tapped. You could then use that information to set the data on the destination view controller.Availability
Available in iOS 5.0 and later.
-
Initiates the segue with the specified identifier from the current view controller's storyboard file.
Declaration
Objective-C
- (void)performSegueWithIdentifier:(NSString *)identifiersender:(id)senderParameters
identifierThe string that identifies the triggered segue. In Interface Builder, you specify the segue’s identifier string in the attributes inspector.
This method throws an exception if there is no segue with the specified identifier.
senderThe object that you want to use to initiate the segue. This object is made available for informational purposes during the actual segue.
Discussion
Normally, segues are initiated automatically and not using this method. However, you can use this method in cases where the segue could not be configured in your storyboard file. For example, you might call it from a custom action handler used in response to shake or accelerometer events.
The current view controller must have been loaded from a storyboard. If its
storyboardproperty isnil, perhaps because you allocated and initialized the view controller yourself, this method throws an exception.Availability
Available in iOS 5.0 and later.
See Also
-
allowedChildViewControllersForUnwindingFromSource(_:) - allowedChildViewControllersForUnwindingFromSource:Returns an array of child view controllers that should be searched for an unwind segue destination.
Declaration
Swift
func allowedChildViewControllersForUnwindingFromSource(_source: UIStoryboardUnwindSegueSource) -> [UIViewController]Objective-C
- (NSArray<UIViewController *> *)allowedChildViewControllersForUnwindingFromSource:(UIStoryboardUnwindSegueSource *)sourceParameters
sourceThe unwind segue source object containing information about the unwind segue.
Return Value
An array of view controllers representing the child view controllers to search. The order of the items in the array determines the search order.
Discussion
UIKit calls this method when searching for the destination of an unwind segue. The default implementation returns the contents of the
childViewControllersproperty minus the view controller returned by thechildViewControllerContainingSegueSource:method. You can override this method as needed in your custom container view controllers to change the search order. For example, a navigation controller reverses the order so that the search starts with the view controller at the top of the navigation stack.Availability
Available in iOS 9.0 and later.
-
Returns the child view controller that contains the source of the unwind segue.
Declaration
Swift
func childViewControllerContainingSegueSource(_source: UIStoryboardUnwindSegueSource) -> UIViewController?Objective-C
- (UIViewController *)childViewControllerContainingSegueSource:(UIStoryboardUnwindSegueSource *)sourceParameters
sourceThe unwind segue source object containing information about the unwind segue.
Return Value
The view controller that contains the segue source.
Discussion
Container view controllers call this method to identify the child view controller that is the source of the unwind segue. Typically, you call this method from your
allowedChildViewControllersForUnwindingFromSource:method so that you can remove the corresponding view controller from the returned list of children.Availability
Available in iOS 9.0 and later.
-
canPerformUnwindSegueAction(_:fromViewController:withSender:) - canPerformUnwindSegueAction:fromViewController:withSender:Called on a view controller to determine whether it wants to respond to an unwind action.
Declaration
Swift
func canPerformUnwindSegueAction(_action: Selector, fromViewControllerfromViewController: UIViewController, withSendersender: AnyObject) -> BoolObjective-C
- (BOOL)canPerformUnwindSegueAction:(SEL)actionfromViewController:(UIViewController *)fromViewControllerwithSender:(id)senderParameters
actionThe unwind action to invoke on your view controller.
fromViewControllerThe view controller that initiated the unwind action.
senderThe object that triggered the action.
Return Value
YEStrueif the view controller wants to handle the unwind action, otherwiseNOfalse.Discussion
When an unwind segue is triggered, UIKit uses this method and the
allowedChildViewControllersForUnwindingFromSource:method to locate a suitable view controller to handle the unwind segue.The default implementation of this method returns
YEStruewhen the current view controller implements theactionmethod and is not the same view controller as the one in thefromViewControllerparameter. You can override this method as needed to change the default behavior. For example, you might returnNOfalseif the current view controller does not make a suitable return target when unwinding from the specified view controller.Availability
Available in iOS 6.0 and later.
-
Called when an unwind segue transitions to a new view controller.
Declaration
Swift
func unwindForSegue(_unwindSegue: UIStoryboardSegue, towardsViewControllersubsequentVC: UIViewController)Objective-C
- (void)unwindForSegue:(UIStoryboardSegue *)unwindSeguetowardsViewController:(UIViewController *)subsequentVCParameters
unwindSegueThe unwind segue being performed.
subsequentVCThe view controller closest to the current controller that represents the transition direction. Container view controllers should configure themselves so that this view controller is displayed.
Discussion
During the execution of an unwind segue, UIKit calls this method on any view controllers in the unwind path to give them an opportunity to reconfigure themselves. Container view controllers must implement this method and use to to display the view controller in the
subsequentVCparameter. For example, a tab bar controller selects the tab containing the specified view controller. Noncontainer view controllers should not override this method.Availability
Available in iOS 9.0 and later.
-
viewControllerForUnwindSegueAction(_:fromViewController:withSender:) - viewControllerForUnwindSegueAction:fromViewController:withSender:(iOS 9.0)Called when an unwind segue action wants to search a container's children for a view controller to handle the unwind action.
Deprecation Statement
Override the
allowedChildViewControllersForUnwindingFromSource:method instead.Declaration
Swift
func viewControllerForUnwindSegueAction(_action: Selector, fromViewControllerfromViewController: UIViewController, withSendersender: AnyObject?) -> UIViewController?Objective-C
- (UIViewController *)viewControllerForUnwindSegueAction:(SEL)actionfromViewController:(UIViewController *)fromViewControllerwithSender:(id)senderParameters
actionThe action that triggered the unwind action.
fromViewControllerThe view controller that is the source of the unwinding action.
senderThe object that initiated the action.
Return Value
The view controller that wants to handle the unwind action.
Discussion
A custom container view controller should override this method and use it to search its children for a view controller to handle the unwind action. It does this by invoking the
canPerformUnwindSegueAction:fromViewController:withSender:method on each child. If a view controller wants to handle the action, your method should return it. If none of the container's children want to handle the unwind action, invoke the super’s implementation and return the result of that method.Availability
Available in iOS 6.0 and later.
Deprecated in iOS 9.0.
-
segueForUnwindingToViewController(_:fromViewController:identifier:) - segueForUnwindingToViewController:fromViewController:identifier:(iOS 9.0)Called when an unwind segue action needs to transition between two view controllers.
Deprecation Statement
Use
unwindForSegue:towardsViewController:instead.Declaration
Swift
func segueForUnwindingToViewController(_toViewController: UIViewController, fromViewControllerfromViewController: UIViewController, identifieridentifier: String?) -> UIStoryboardSegue?Objective-C
- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewControllerfromViewController:(UIViewController *)fromViewControlleridentifier:(NSString *)identifierParameters
toViewControllerThe target view controller.
fromViewControllerThe view controller initiating the unwind action.
identifierAn identifier for the segue.
Return Value
A segue object for managing the transitions between the two view controllers.
Discussion
If you implement a custom container view controller that also uses segue unwinding, you must override this method. In your custom implementation, instantiate and return a segue object that performs whatever animation and other steps that are necessary to unwind the view controllers.
You do not need to override this method for view controllers that are not containers.
Availability
Available in iOS 6.0 and later.
Deprecated in iOS 9.0.
-
The view that the controller manages.
Discussion
The view stored in this property represents the root view for the view controller's view hierarchy. The default value of this property is
nil.If you access this property and its value is currently
nil, the view controller automatically calls theloadViewmethod and returns the resulting view.Each view controller object is the sole owner of its view. You must not associate the same view object with multiple view controller objects. The only exception to this rule is that a container view controller implementation may add this view as a subview in its own view hierarchy. Before adding the subview, the container must first call its
addChildViewController:method to create a parent-child relationship between the two view controller objects.Because accessing this property can cause the view to be loaded automatically, you can use the
isViewLoadedmethod to determine if the view is currently in memory. Unlike this property, theisViewLoadedproperty does not force the loading of the view if it is not currently in memory.The
UIViewControllerclass can automatically set this property tonilduring low-memory conditions and also when the view controller itself is finally released.For more information about how a view controller loads and unloads its view, see Resource Management in View Controllers.
Availability
Available in iOS 2.0 and later.
-
Returns a Boolean value indicating whether the view is currently loaded into memory.
Return Value
A Boolean value indicating whether the view is currently loaded into memory.
Discussion
Calling this method reports whether the view is loaded. Unlike the
viewproperty, it does not attempt to load the view if it is not already in memory.Availability
Available in iOS 3.0 and later.
See Also
-
Creates the view that the controller manages.
Declaration
Swift
func loadView()Objective-C
- (void)loadViewDiscussion
You should never call this method directly. The view controller calls this method when its
viewproperty is requested but is currentlynil. This method loads or creates a view and assigns it to theviewproperty.If the view controller has an associated nib file, this method loads the view from the nib file. A view controller has an associated nib file if the
nibNameproperty returns a non-nilvalue, which occurs if the view controller was instantiated from a storyboard, if you explicitly assigned it a nib file using theinitWithNibName:bundle:method, or if iOS finds a nib file in the app bundle with a name based on the view controller's class name. If the view controller does not have an associated nib file, this method creates a plainUIViewobject instead.If you use Interface Builder to create your views and initialize the view controller, you must not override this method.
You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the
viewproperty. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not callsuper.If you want to perform any additional initialization of your views, do so in the
viewDidLoadmethod.Availability
Available in iOS 2.0 and later.
-
Called after the controller's view is loaded into memory.
Declaration
Swift
func viewDidLoad()Objective-C
- (void)viewDidLoadDiscussion
This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the
loadViewmethod. You usually override this method to perform additional initialization on views that were loaded from nib files.Availability
Available in iOS 2.0 and later.
See Also
-
Loads the view controller’s view if it has not yet been loaded.
Declaration
Swift
func loadViewIfNeeded()Objective-C
- (void)loadViewIfNeededDiscussion
Calling this method loads the view controller’s view from its storyboard file, or creates the view as needed based on the established rules.
Availability
Available in iOS 9.0 and later.
-
viewIfLoaded viewIfLoadedPropertyThe view controller’s view, or
nilif the view is not yet loaded. (read-only)Declaration
Swift
var viewIfLoaded: UIView? { get }Objective-C
@property(nonatomic, readonly, strong) UIView *viewIfLoadedDiscussion
If the view controller’s view has already been loaded, this property contains that view. If the view has not yet been loaded, this property is set to
nil.Availability
Available in iOS 9.0 and later.
-
A localized string that represents the view this controller manages.
Discussion
Set the title to a human-readable string that describes the view. If the view controller has a valid navigation item or tab-bar item, assigning a value to this property updates the title text those objects.
Availability
Available in iOS 2.0 and later.
-
preferredContentSize preferredContentSizePropertyThe preferred size for the view controller’s view.
Declaration
Swift
var preferredContentSize: CGSizeObjective-C
@property(nonatomic) CGSize preferredContentSizeDiscussion
The value in this property is used primarily when displaying the view controller’s content in a popover but may also be used in other situations. Changing the value of this property while the view controller is being displayed in a popover animates the size change; however, the change is not animated if you specify a width or height of
0.0.Availability
Available in iOS 7.0 and later.
-
The presentation style for modally presented view controllers.
Declaration
Swift
var modalPresentationStyle: UIModalPresentationStyleObjective-C
@property(nonatomic, assign) UIModalPresentationStyle modalPresentationStyleDiscussion
The presentation style determines how a modally presented view controller is displayed onscreen. In a horizontally compact environment, modal view controllers are always presented full-screen. In a horizontally regular environment, there are several different presentation options. For a list of possible presentation styles, and their compatibility with the available transition styles, see the
UIModalPresentationStyleconstant descriptions.Availability
Available in iOS 3.2 and later.
See Also
-
modalTransitionStyle modalTransitionStylePropertyThe transition style to use when presenting the view controller.
Declaration
Swift
var modalTransitionStyle: UIModalTransitionStyleObjective-C
@property(nonatomic, assign) UIModalTransitionStyle modalTransitionStyleDiscussion
This property determines how the view controller's is animated onscreen when it is presented using the
presentViewController:animated:completion:method. To change the transition type, you must set this property before presenting the view controller. The default value for this property isUIModalTransitionStyleCoverVertical.For a list of possible transition styles, and their compatibility with the available presentation styles, see the
UIModalTransitionStyleconstant descriptions.Availability
Available in iOS 3.0 and later.
-
modalInPopover modalInPopoverPropertyA Boolean value indicating whether the view controller should be presented modally by a popover.
Declaration
Swift
var modalInPopover: BoolObjective-C
@property(nonatomic, readwrite, getter=isModalInPopover) BOOL modalInPopoverDiscussion
The default value of this property is
NOfalse. Setting it toYEStruecauses an owning popover controller to disallow interactions outside this view controller while it is displayed. You can use this behavior to ensure that the popover is not dismissed by taps outside the popover controller.Availability
Available in iOS 3.2 and later.
-
Presents a view controller in a primary context.
Declaration
Swift
func showViewController(_vc: UIViewController, sendersender: AnyObject?)Objective-C
- (void)showViewController:(UIViewController *)vcsender:(id)senderParameters
vcThe view controller to display.
senderThe object that initiated the request.
Discussion
You use this method to decouple the need to display a view controller from the process of actually presenting that view controller onscreen. Using this method, a view controller does not need to know whether it is embedded inside a navigation controller or split-view controller. It calls the same method for both. The
UISplitViewControllerandUINavigationControllerclasses override this method and handle the presentation according to their design. For example, a navigation controller overrides this method and uses it to pushvconto its navigation stack.The default implementation of this method calls the
targetViewControllerForAction:sender:method to locate an object in the view controller hierarchy that overrides this method. It then calls the method on that target object, which displays the view controller in an appropriate way. If thetargetViewControllerForAction:sender:method returnsnil, this method uses the window’s root view controller to presentvcmodally.You can override this method in custom view controllers to display
vcyourself. Use this method to displayvcin a primary context. For example, a container view controller might use this method to replace its primary child. Your implementation should adapt its behavior for both regular and compact environments.Availability
Available in iOS 8.0 and later.
-
Presents a view controller in a secondary (or detail) context.
Declaration
Swift
func showDetailViewController(_vc: UIViewController, sendersender: AnyObject?)Objective-C
- (void)showDetailViewController:(UIViewController *)vcsender:(id)senderParameters
vcThe current view controller.
senderThe object being acted upon.
Discussion
You use this method to decouple the need to display a view controller from the process of actually presenting that view controller onscreen. Using this method, a view controller does not need to know whether it is embedded inside a navigation controller or split-view controller. It calls the same method for both. In a regular environment, the
UISplitViewControllerclass overrides this method and installsvcas its detail view controller; in a compact environment, the split view controller’s implementation of this method callsshowViewController:sender:instead.The default implementation of this method calls the
targetViewControllerForAction:sender:method to locate an object in the view controller hierarchy that overrides this method. It then calls the method on that target object, which displays the view controller in an appropriate way. If thetargetViewControllerForAction:sender:method returnsnil, this method uses the window’s root view controller to presentvcmodally.You can override this method in custom view controllers to display
vcyourself. Use this method to displayvcin a secondary context. For example, a container view controller might use this method to replace its secondary child. Your implementation should adapt its behavior for both regular and compact environments.Availability
Available in iOS 8.0 and later.
-
Presents a view controller modally.
Declaration
Swift
func presentViewController(_viewControllerToPresent: UIViewController, animatedflag: Bool, completioncompletion: (() -> Void)?)Objective-C
- (void)presentViewController:(UIViewController *)viewControllerToPresentanimated:(BOOL)flagcompletion:(void (^)(void))completionParameters
viewControllerToPresentThe view controller to display over the current view controller’s content.
flagPass
YEStrueto animate the presentation; otherwise, passNOfalse.completionThe block to execute after the presentation finishes. This block has no return value and takes no parameters. You may specify
nilfor this parameter.Discussion
In a horizontally regular environment, the view controller is presented in the style specified by the
modalPresentationStyleproperty. In a horizontally compact environment, the view controller is presented full screen by default. If you associate an adaptive delegate with the presentation controller associated with the object inviewControllerToPresent, you can modify the presentation style dynamically.The object on which you call this method may not always be the one that handles the presentation. Each presentation style has different rules governing its behavior. For example, a full-screen presentation must be made by a view controller that itself covers the entire screen. If the current view controller is unable to fulfill a request, it forwards the request up the view controller hierarchy to its nearest parent, which can then handle or forward the request.
Before displaying the view controller, this method resizes the presented view controller's view based on the presentation style. For most presentation styles, the resulting view is then animated onscreen using the transition style in the
modalTransitionStyleproperty of the presented view controller. For custom presentations, the view is animated onscreen using the presented view controller’s transitioning delegate. For current context presentations, the view may be animated onscreen using the current view controller’s transition style.The completion handler is called after the
viewDidAppear:method is called on the presented view controller.Availability
Available in iOS 5.0 and later.
-
Dismisses the view controller that was presented modally by the view controller.
Declaration
Objective-C
- (void)dismissViewControllerAnimated:(BOOL)flagcompletion:(void (^)(void))completionParameters
flagPass
YEStrueto animate the transition.completionThe block to execute after the view controller is dismissed. This block has no return value and takes no parameters. You may specify
nilfor this parameter.Discussion
The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.
If you present several view controllers in succession, thus building a stack of presented view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack. When this happens, only the top-most view is dismissed in an animated fashion; any intermediate view controllers are simply removed from the stack. The top-most view is dismissed using its modal transition style, which may differ from the styles used by other view controllers lower in the stack.
If you want to retain a reference to the view controller's presented view controller, get the value in the
presentedViewControllerproperty before calling this method.The completion handler is called after the
viewDidDisappear:method is called on the presented view controller.Availability
Available in iOS 5.0 and later.
-
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.
Declaration
Swift
var definesPresentationContext: BoolObjective-C
@property(nonatomic, assign) BOOL definesPresentationContextDiscussion
When using the
UIModalPresentationCurrentContextorUIModalPresentationOverCurrentContextstyle to present a view controller, this property controls which existing view controller in your view controller hierarchy is actually covered by the new content. When a context-based presentation occurs, UIKit starts at the presenting view controller and walks up the view controller hierarchy. If it finds a view controller whose value for this property isYEStrue, it asks that view controller to present the new view controller. If no view controller defines the presentation context, UIKit asks the window’s root view controller to handle the presentation.The default value for this property is
NOfalse. Some system-provided view controllers, such asUINavigationController, change the default value toYEStrue.Availability
Available in iOS 5.0 and later.
-
A Boolean value that indicates whether the view controller specifies the transition style for view controllers it presents.
Declaration
Swift
var providesPresentationContextTransitionStyle: BoolObjective-C
@property(nonatomic, assign) BOOL providesPresentationContextTransitionStyleDiscussion
When a view controller’s
definesPresentationContextproperty isYEStrue, it can replace the transition style of the presented view controller with its own. When the value of this property toYEStrue, the current view controller’s transition style is used instead of the style associated with the presented view controller. When the value of this property isNOfalse, UIKit uses the transition style of the presented view controller. The default value of this property isNOfalse.Availability
Available in iOS 5.0 and later.
See Also
-
Returns a Boolean indicating whether the current input view is dismissed automatically when changing controls.
Declaration
Swift
func disablesAutomaticKeyboardDismissal() -> BoolObjective-C
- (BOOL)disablesAutomaticKeyboardDismissalReturn Value
YEStrueto prevent the dismissal of the input view orNOfalseif the input view may be dismissed.Discussion
Override this method in a subclass to allow or disallow the dismissal of the current input view (usually the system keyboard) when changing from a control that wants the input view to one that does not. Under normal circumstances, when the user taps a control that requires an input view, the system automatically displays that view. Tapping in a control that does not want an input view subsequently causes the current input view to be dismissed but may not in all cases. You can override this method in those outstanding cases to allow the input view to be dismissed or use this method to prevent the view from being dismissed in other cases.
The default implementation of this method returns
YEStruewhen the modal presentation style of the view controller is set toUIModalPresentationFormSheetand returnsNOfalsefor other presentation styles. Thus, the system normally does not allow the keyboard to be dismissed for modal forms.Availability
Available in iOS 4.3 and later.
-
The delegate object that provides transition animator, interactive controller, and custom presentation controller objects.
Declaration
Swift
weak var transitioningDelegate: UIViewControllerTransitioningDelegate?Objective-C
@property(nonatomic, weak) id< UIViewControllerTransitioningDelegate > transitioningDelegateDiscussion
When the view controller’s
modalPresentationStyleproperty isUIModalPresentationCustom, UIKit uses the object in this property to facilitate transitions and presentations for the view controller. The transitioning delegate object is a custom object that you provide and that conforms to theUIViewControllerTransitioningDelegateprotocol. Its job is to vend the animator objects used to animate this view controller’s view onscreen and an optional presentation controller to provide any additional chrome and animations.Availability
Available in iOS 7.0 and later.
-
Returns the active transition coordinator object.
Declaration
Swift
func transitionCoordinator() -> UIViewControllerTransitionCoordinator?Objective-C
- (id<UIViewControllerTransitionCoordinator>)transitionCoordinatorReturn Value
The transition coordinator object associated with a currently active transition or
nilif no transition is in progress.Discussion
When a presentation or dismissal is in progress, this method returns the transition coordinator object associated with that transition. If there is no in-progress transition associated with the current view controller, UIKit checks the view controller’s ancestors for a transition coordinator object and returns that object if it exists. You can use this object to create additional animations and synchronize them with the transition animations.
Container view controllers can override this method but in most cases should not need to. If you do override this method, first call
superto see if there is an appropriate transition coordinator to return, and, if there is, return it.For more information about the role of transition coordinators, see UIViewControllerTransitionCoordinator Protocol Reference.
Availability
Available in iOS 7.0 and later.
-
Returns the view controller that responds to the action.
Declaration
Swift
func targetViewControllerForAction(_action: Selector, sendersender: AnyObject?) -> UIViewController?Objective-C
- (UIViewController *)targetViewControllerForAction:(SEL)actionsender:(id)senderParameters
actionThe requested action.
senderThe object sending the request.
Return Value
The view controller that handles the specified action or
nilif no view controller handles the action.Discussion
This method returns the current view controller if that view controller overrides the method indicated by the
actionparameter. If the current view controller does not override that method, UIKit walks up the view hierarchy and returns the first view controller that does override it. If no view controller handles the action, this method returnsnil.A view controller can selectively respond to an action by returning an appropriate value from its
canPerformAction:withSender:method.Availability
Available in iOS 8.0 and later.
-
The nearest presentation controller that is managing the current view controller. (read-only)
Declaration
Swift
var presentationController: UIPresentationController? { get }Objective-C
@property(nonatomic, readonly) UIPresentationController *presentationControllerDiscussion
If the view controller or one of its ancestors is managed by a presentation controller, this property contains that object. This property is
nilif the view controller is not managed by a presentation controller.If you have not yet presented the current view controller, accessing this property creates a presentation controller based on the current value in the
modalPresentationStyleproperty. Always set the value of that property before accessing any presentation controllers.Availability
Available in iOS 8.0 and later.
See Also
-
The nearest popover presentation controller that is managing the current view controller. (read-only)
Declaration
Swift
var popoverPresentationController: UIPopoverPresentationController? { get }Objective-C
@property(nonatomic, readonly) UIPopoverPresentationController *popoverPresentationControllerDiscussion
If the view controller or one of its ancestors is managed by a popover presentation controller, this property contains that object. This property is
nilif the view controller is not managed by a popover presentation controller.If you created the view controller but have not yet presented it, accessing this property creates a popover presentation controller when the value in the
modalPresentationStyleproperty isUIModalPresentationPopover. If the modal presentation style is a different value, this property isnil.Availability
Available in iOS 8.0 and later.
See Also
-
Notifies the view controller that its view is about to be added to a view hierarchy.
Declaration
Swift
func viewWillAppear(_animated: Bool)Objective-C
- (void)viewWillAppear:(BOOL)animatedParameters
animatedIf
YEStrue, the view is being added to the window using an animation.Discussion
This method is called before the view controller's view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call
superat some point in your implementation.For more information about the how views are added to view hierarchies by a view controller, and the sequence of messages that occur, see Responding to Display-Related Notifications.
Availability
Available in iOS 2.0 and later.
See Also
-
Notifies the view controller that its view was added to a view hierarchy.
Declaration
Swift
func viewDidAppear(_animated: Bool)Objective-C
- (void)viewDidAppear:(BOOL)animatedParameters
animatedIf
YEStrue, the view was added to the window using an animation.Discussion
You can override this method to perform additional tasks associated with presenting the view. If you override this method, you must call
superat some point in your implementation.Availability
Available in iOS 2.0 and later.
See Also
-
Notifies the view controller that its view is about to be removed from a view hierarchy.
Declaration
Swift
func viewWillDisappear(_animated: Bool)Objective-C
- (void)viewWillDisappear:(BOOL)animatedParameters
animatedIf
YEStrue, the disappearance of the view is being animated.Discussion
This method is called in response to a view being removed from a view hierarchy. This method is called before the view is actually removed and before any animations are configured.
Subclasses can override this method and use it to commit editing changes, resign the first responder status of the view, or perform other relevant tasks. For example, you might use this method to revert changes to the orientation or style of the status bar that were made in the
viewDidDisappear:method when the view was first presented. If you override this method, you must callsuperat some point in your implementation.Availability
Available in iOS 2.0 and later.
See Also
-
Notifies the view controller that its view was removed from a view hierarchy.
Declaration
Swift
func viewDidDisappear(_animated: Bool)Objective-C
- (void)viewDidDisappear:(BOOL)animatedParameters
animatedIf
YEStrue, the disappearance of the view was animated.Discussion
You can override this method to perform additional tasks associated with dismissing or hiding the view. If you override this method, you must call
superat some point in your implementation.Availability
Available in iOS 2.0 and later.
See Also
-
Called to notify the view controller that its view is about to layout its subviews.
Declaration
Swift
func viewWillLayoutSubviews()Objective-C
- (void)viewWillLayoutSubviewsDiscussion
When a view's bounds change, the view adjusts the position of its subviews. Your view controller can override this method to make changes before the view lays out its subviews. The default implementation of this method does nothing.
Availability
Available in iOS 5.0 and later.
-
Called to notify the view controller that its view has just laid out its subviews.
Declaration
Swift
func viewDidLayoutSubviews()Objective-C
- (void)viewDidLayoutSubviewsDiscussion
When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.
Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing.
Availability
Available in iOS 5.0 and later.
-
Called when the view controller's view needs to update its constraints.
Declaration
Swift
func updateViewConstraints()Objective-C
- (void)updateViewConstraintsDiscussion
Override this method to optimize changes to your constraints.
To schedule a change, call
setNeedsUpdateConstraintson the view. The system then calls your implementation ofupdateViewConstraintsbefore the layout occurs. This lets you verify that all necessary constraints for your content are in place at a time when your properties are not changing.Your implementation must be as efficient as possible. Do not deactivate all your constraints, then reactivate the ones you need. Instead, your app must have some way of tracking your constraints, and validating them during each update pass. Only change items that need to be changed. During each update pass, you must ensure that you have the appropriate constraints for the app’s current state.
Do not call
setNeedsUpdateConstraintsinside your implementation. CallingsetNeedsUpdateConstraintsschedules another update pass, creating a feedback loop.Availability
Available in iOS 6.0 and later.
-
bottomLayoutGuide bottomLayoutGuidePropertyIndicates the lowest vertical extent for your onscreen content, for use with Auto Layout constraints. (read-only)
Declaration
Swift
var bottomLayoutGuide: UILayoutSupport { get }Objective-C
@property(nonatomic, readonly, strong) id< UILayoutSupport > bottomLayoutGuideDiscussion
The
bottomLayoutGuideproperty comes into play when a view controller is frontmost onscreen. It indicates the lowest vertical extent for content that you don't want to appear behind a translucent or transparent UIKit bar (such as a tab bar or toolbar). This property implements theUILayoutSupportprotocol and you can employ it as a constraint item when using theNSLayoutConstraintclass.The value of this property is, specifically, the value of the
lengthproperty of the object returned when you query this property. This value is constrained by either the view controller or by its enclosing container view controller (such as a navigation or tab bar controller), as follows:A view controller not within a container view controller constrains this property to indicate the top of the tab bar or toolbar, if one of these is visible, or else to indicate the bottom edge of the view controller's view.
A view controller within a container view controller does not set this property’s value. Instead, the container view controller constrains the value to indicate the top of the tab bar or toolbar, if one of these is visible, or else to indicate the bottom edge of the view controller's view.
If a container view controller's toolbar or tab bar is visible and opaque, the container lays out the frontmost view controller's view so its bottom edge abuts the top of the bar. In this case, the value of this property is 0.
Query this property within your implementation of the
viewDidLayoutSubviewsmethod.When laying out a storyboard scene, the Bottom Layout Guide object is available in the Interface Builder outline view as a child of the View Controller object. Adding a bottom layout guide using Interface Builder provides backward layout compatibility to iOS 6.
As an example of how to programmatically use this property with Auto Layout, say you want to position a control such that its bottom edge is 20 points above the bottom layout guide. This scenario applies to any of the scenarios listed above. Use code similar to the following:
[button setTranslatesAutoresizingMaskIntoConstraints: NO];id bottomGuide = myViewController.bottomLayoutGuide;NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, bottomGuide);[myViewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat: @"V: [button]-20-[bottomGuide]"options: 0metrics: nilviews: viewsDictionary]];[self.view layoutSubviews]; // You must call this method here or the system raises an exception
To use a bottom layout guide without using constraints, obtain the guide’s position relative to the bottom bound of the containing view. In the case of using a view controller subclass, obtain the numbers you need as follows:
- (void) viewDidLayoutSubviews {CGRect viewBounds = self.view.bounds;CGFloat bottomBarOffset = self.bottomLayoutGuide.length;}
In the case of using a view subclass, obtain the numbers you need as follows:
- (void) layoutSubviews {[super layoutSubviews]; // You must call super here or the system raises an exceptionCGRect bounds = self.bounds;CGFloat bottomBarOffset = myVCReference.bottomLayoutGuide.length;}
For more guidance on using view controllers in iOS 7, read Using View Controllers in iOS 7 UI Transition Guide.
Availability
Available in iOS 7.0 and later.
See Also
-
topLayoutGuide topLayoutGuidePropertyIndicates the highest vertical extent for your onscreen content, for use with Auto Layout constraints. (read-only)
Declaration
Swift
var topLayoutGuide: UILayoutSupport { get }Objective-C
@property(nonatomic, readonly, strong) id< UILayoutSupport > topLayoutGuideDiscussion
The
topLayoutGuideproperty comes into play when a view controller is frontmost onscreen. It indicates the highest vertical extent for content that you don't want to appear behind a translucent or transparent UIKit bar (such as a status or navigation bar). This property implements theUILayoutSupportprotocol and you can employ it as a constraint item when using theNSLayoutConstraintclass.The value of this property is, specifically, the value of the
lengthproperty of the object returned when you query this property. This value is constrained by either the view controller or by its enclosing container view controller (such as a navigation or tab bar controller), as follows:A view controller not within a container view controller constrains this property to indicate the bottom of the status bar, if visible, or else to indicate the top edge of the view controller's view.
A view controller within a container view controller does not set this property's value. Instead, the container view controller constrains the value to indicate:
The bottom of the navigation bar, if a navigation bar is visible
The bottom of the status bar, if only a status bar is visible
The top edge of the view controller's view, if neither a status bar nor navigation bar is visible
If a container navigation controller's navigation bar is visible and opaque, the navigation controller lays out the frontmost view controller's view so its top edge abuts the bottom of the navigation bar. In this case, the value of this property is
0.Query this property within your implementation of the
viewDidLayoutSubviewsmethod.When laying out a storyboard scene, the Top Layout Guide object is available in the Interface Builder outline view as a child of the View Controller object. Adding a top layout guide using Interface Builder provides backward compatibility to iOS 6.
As an example of how to programmatically use this property with Auto Layout, say you want to position a control such that its top edge is 20 points below the top layout guide. This scenario applies to any of the scenarios listed above. Use code similar to the following:
[button setTranslatesAutoresizingMaskIntoConstraints: NO];id topGuide = myViewController.topLayoutGuide;NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);[myViewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat: @"V:[topGuide]-20-[button]"options: 0metrics: nilviews: viewsDictionary]];[self.view layoutSubviews]; // You must call this method here or the system raises an exception
To use a top layout guide without using constraints, obtain the guide’s position relative to the top bound of the containing view. In the case of using a view controller subclass, obtain the numbers you need as follows:
- (void) viewDidLayoutSubviews {CGRect viewBounds = self.view.bounds;CGFloat topBarOffset = self.topLayoutGuide.length;}
In the case of using a view subclass, obtain the numbers you need as follows:
- (void) layoutSubviews {[super layoutSubviews]; // You must call super here or the system raises an exceptionCGRect bounds = self.bounds;CGFloat topBarOffset = myVCReference.topLayoutGuide.length;}
For more guidance on using view controllers in iOS 7, read Using View Controllers in iOS 7 UI Transition Guide.
Availability
Available in iOS 7.0 and later.
See Also
-
The extended edges to use for the layout.
Declaration
Swift
var edgesForExtendedLayout: UIRectEdgeObjective-C
@property(nonatomic, assign) UIRectEdge edgesForExtendedLayoutDiscussion
This property is applied only to view controllers that are embedded in a container such as
UINavigationController. The window’s root view controller does not react to this property. The default value of this property isUIRectEdgeAll.Availability
Available in iOS 7.0 and later.
-
A Boolean value indicating whether or not the extended layout includes opaque bars.
Declaration
Swift
var extendedLayoutIncludesOpaqueBars: BoolObjective-C
@property(nonatomic, assign) BOOL extendedLayoutIncludesOpaqueBarsAvailability
Available in iOS 7.0 and later.
-
A Boolean value that indicates whether the view controller should automatically adjust its scroll view insets.
Declaration
Swift
var automaticallyAdjustsScrollViewInsets: BoolObjective-C
@property(nonatomic, assign) BOOL automaticallyAdjustsScrollViewInsetsDiscussion
The default value of this property is
YEStrue, which lets container view controllers know that they should adjust the scroll view insets of this view controller’s view to account for screen areas consumed by a status bar, search bar, navigation bar, toolbar, or tab bar. Set this property toNOfalseif your view controller implementation manages its own scroll view inset adjustments.Availability
Available in iOS 7.0 and later.
-
Returns a Boolean value that indicates that the view controller is in the process of being removed from its parent.
Declaration
Swift
func isMovingFromParentViewController() -> BoolObjective-C
- (BOOL)isMovingFromParentViewControllerReturn Value
YEStrueif the view controller is disappearing because it was removed from a container view controller, otherwiseNOfalse.Discussion
This method returns
YEStrueonly when called from inside theviewWillDisappear:andviewDidDisappear:methods.Availability
Available in iOS 5.0 and later.
-
Returns a Boolean value that indicates that the view controller is in the process of being added to a parent.
Declaration
Swift
func isMovingToParentViewController() -> BoolObjective-C
- (BOOL)isMovingToParentViewControllerReturn Value
YEStrueif the view controller is appearing because it was added as a child of a container view controller, otherwiseNOfalse.Discussion
This method returns
YEStrueonly when called from inside theviewWillAppear:andviewDidAppear:methods.Availability
Available in iOS 5.0 and later.
-
Returns a Boolean value that indicates whether the view controller is in the process of being presented by one of its ancestors.
Return Value
YEStrueif the view controller is appearing because it was presented by another view controller, otherwiseNOfalse.Discussion
This method returns
YEStrueonly when called from inside theviewWillAppear:andviewDidAppear:methods.Availability
Available in iOS 5.0 and later.
-
Returns a Boolean value that indicates whether the view controller is in the process of being dismissed by one of its ancestors.
Return Value
YEStrueif the view controller was previously presented and is in the process of being dismissed by one of its ancestors, otherwiseNOfalse.Discussion
This method returns
YEStrueonly when called from inside theviewWillDisappear:andviewDidDisappear:methods.Availability
Available in iOS 5.0 and later.
-
Returns a Boolean value indicating whether the view controller's contents should auto rotate.
Return Value
YEStrueif the content should rotate, otherwiseNOfalse. This method returnsYEStrueby default.Special Considerations
In iOS 5 and earlier, the default return value was
NOfalse.Availability
Available in iOS 6.0 and later.
-
Returns all of the interface orientations that the view controller supports.
Declaration
Swift
func supportedInterfaceOrientations() -> UIInterfaceOrientationMaskObjective-C
- (UIInterfaceOrientationMask)supportedInterfaceOrientationsReturn Value
A bit mask specifying which orientations are supported. See
UIInterfaceOrientationMaskfor valid bit-mask values. The value returned by this method must not be0.Discussion
When the user changes the device orientation, the system calls this method on the root view controller or the topmost presented view controller that fills the window. If the view controller supports the new orientation, the window and view controller are rotated to the new orientation. This method is only called if the view controller's
shouldAutorotatemethod returnsYEStrue.Override this method to report all of the orientations that the view controller supports. The default values for a view controller's supported interface orientations is set to
UIInterfaceOrientationMaskAllfor the iPad idiom andUIInterfaceOrientationMaskAllButUpsideDownfor the iPhone idiom.The system intersects the view controller's supported orientations with the app's supported orientations (as determined by the Info.plist file or the app delegate's
application:supportedInterfaceOrientationsForWindow:method) to determine whether to rotate.Availability
Available in iOS 6.0 and later.
See Also
-
Returns the interface orientation to use when presenting the view controller.
Declaration
Swift
func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientationObjective-C
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentationReturn Value
The interface orientation with which to present the view controller.
Discussion
The system calls this method when presenting the view controller full screen. When your view controller supports two or more orientations but the content appears best in one of those orientations, override this method and return the preferred orientation.
If your view controller implements this method, your view controller’s view is shown in the preferred orientation (although it can later be rotated to another supported rotation). If you do not implement this method, the system presents the view controller using the current orientation of the status bar.
Availability
Available in iOS 6.0 and later.
-
Attempts to rotate all windows to the orientation of the device.
Declaration
Swift
class func attemptRotationToDeviceOrientation()Objective-C
+ (void)attemptRotationToDeviceOrientationDiscussion
Some view controllers may want to use app-specific conditions to determine what interface orientations are supported. If your view controller does this, when those conditions change, your app should call this class method. The system immediately attempts to rotate to the new orientation.
Availability
Available in iOS 5.0 and later.
See Also
-
collapseSecondaryViewController(_:forSplitViewController:) - collapseSecondaryViewController:forSplitViewController:Called when a split view controller transitions to a compact-width size class.
Declaration
Swift
func collapseSecondaryViewController(_secondaryViewController: UIViewController, forSplitViewControllersplitViewController: UISplitViewController)Objective-C
- (void)collapseSecondaryViewController:(UIViewController *)secondaryViewControllerforSplitViewController:(UISplitViewController *)splitViewControllerParameters
secondaryViewControllerThe secondary view controller associated with the split view controller.
splitViewControllerThe current split view controller.
Discussion
This method provides default behavior when you do not overwrite the
splitViewController:collapseSecondaryViewController:ontoPrimaryViewController:method. The primary view controller associated with the split view controller is displayed.Availability
Available in iOS 8.0 and later.
-
separateSecondaryViewControllerForSplitViewController(_:) - separateSecondaryViewControllerForSplitViewController:Called when a split view controller transitions to a regular-width size class.
Declaration
Swift
func separateSecondaryViewControllerForSplitViewController(_splitViewController: UISplitViewController) -> UIViewController?Objective-C
- (UIViewController *)separateSecondaryViewControllerForSplitViewController:(UISplitViewController *)splitViewControllerParameters
splitViewControllerThe current split view controller.
Return Value
The designated secondary view controller for the split view controller.
Discussion
This method provides default behavior when you do not overwrite the
splitViewController:separateSecondaryViewControllerFromPrimaryViewController:method. The previous secondary view controller is returned.Availability
Available in iOS 8.0 and later.
-
childViewControllers childViewControllersPropertyAn array of view controllers that are children of the current view controller. (read-only)
Declaration
Swift
var childViewControllers: [UIViewController] { get }Objective-C
@property(nonatomic, readonly) NSArray <__kindof UIViewController *> *childViewControllersDiscussion
This property does not include any presented view controllers. This property is only intended to be read by an implementation of a custom container view controller.
Availability
Available in iOS 5.0 and later.
-
Adds the specified view controller as a child of the current view controller.
Declaration
Swift
func addChildViewController(_childController: UIViewController)Objective-C
- (void)addChildViewController:(UIViewController *)childControllerParameters
childControllerThe view controller to be added as a child.
Discussion
This method creates a parent-child relationship between the current view controller and the object in the
childControllerparameter. This relationship is necessary when embedding the child view controller’s view into the current view controller’s content. If the new child view controller is already the child of a container view controller, it is removed from that container before being added.This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call
superin your implementation.Availability
Available in iOS 5.0 and later.
-
Removes the view controller from its parent.
Declaration
Swift
func removeFromParentViewController()Objective-C
- (void)removeFromParentViewControllerDiscussion
This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call
superin your implementation.Availability
Available in iOS 5.0 and later.
-
transitionFromViewController(_:toViewController:duration:options:animations:completion:) - transitionFromViewController:toViewController:duration:options:animations:completion:Transitions between two of the view controller's child view controllers.
Declaration
Swift
func transitionFromViewController(_fromViewController: UIViewController, toViewControllertoViewController: UIViewController, durationduration: NSTimeInterval, optionsoptions: UIViewAnimationOptions, animationsanimations: (() -> Void)?, completioncompletion: ((Bool) -> Void)?)Objective-C
- (void)transitionFromViewController:(UIViewController *)fromViewControllertoViewController:(UIViewController *)toViewControllerduration:(NSTimeInterval)durationoptions:(UIViewAnimationOptions)optionsanimations:(void (^)(void))animationscompletion:(void (^)(BOOL finished))completionParameters
fromViewControllerA view controller whose view is currently visible in the parent's view hierarchy.
toViewControllerA child view controller whose view is not currently in the view hierarchy.
durationThe total duration of the animations, in seconds. If you pass zero, the changes are made without animating them.
optionsA mask of options indicating how you want to perform the animations. For a list of valid constants, see
UIViewAnimationOptions.animationsA block object containing the changes to commit to the views. Here you programmatically change any animatable properties of the views in your view hierarchy. This block takes no parameters and has no return value. This parameter must not be
NULL.completionA block to be called when the animation completes.
The block takes the following parameters:
finishedYEStrueif the animation finished;NOfalseif it was skipped.Discussion
This method adds the second view controller's view to the view hierarchy and then performs the animations defined in your animations block. After the animation completes, it removes the first view controller's view from the view hierarchy.
This method is only intended to be called by an implementation of a custom container view controller. If you override this method, you must call
superin your implementation.Availability
Available in iOS 5.0 and later.
-
Returns a Boolean value indicating whether appearance methods are forwarded to child view controllers.
Declaration
Swift
func shouldAutomaticallyForwardAppearanceMethods() -> BoolObjective-C
- (BOOL)shouldAutomaticallyForwardAppearanceMethodsReturn Value
YEStrueif appearance methods are forwarded orNOfalseif they are not.Discussion
This method is called to determine whether to automatically forward appearance-related containment callbacks to child view controllers.
The default implementation returns
YEStrue. Subclasses of theUIViewControllerclass that implement containment logic may override this method to control how these methods are forwarded. If you override this method and returnNOfalse, you are responsible for telling the child when its views are going to appear or disappear. You do this by calling the child view controller'sbeginAppearanceTransition:animated:andendAppearanceTransitionmethods.Availability
Available in iOS 6.0 and later.
-
Tells a child controller its appearance is about to change.
Declaration
Objective-C
- (void)beginAppearanceTransition:(BOOL)isAppearinganimated:(BOOL)animatedParameters
isAppearingYEStrueif the child view controller's view is about to be added to the view hierarchy,NOfalseif it is being removed.animatedIf
YEStrue, the transition is being animated.Discussion
If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke
viewWillAppear:,viewWillDisappear:,viewDidAppear:, orviewDidDisappear:directly.Availability
Available in iOS 5.0 and later.
See Also
-
Tells a child controller its appearance has changed.
Declaration
Swift
func endAppearanceTransition()Objective-C
- (void)endAppearanceTransitionDiscussion
If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.
Availability
Available in iOS 5.0 and later.
-
setOverrideTraitCollection(_:forChildViewController:) - setOverrideTraitCollection:forChildViewController:Changes the traits assigned to the specified child view controller.
Declaration
Swift
func setOverrideTraitCollection(_collection: UITraitCollection?, forChildViewControllerchildViewController: UIViewController)Objective-C
- (void)setOverrideTraitCollection:(UITraitCollection *)collectionforChildViewController:(UIViewController *)childViewControllerParameters
collectionThe new traits to apply to the child view controller.
childViewControllerThe child view controller who’s trait collection is to be changed.
Discussion
Normally, traits are passed unmodified from the parent view controller to its child view controllers. When implementing a custom container view controller, you can use this method to change the traits of any embedded child view controllers to something more appropriate for your layout. Making such a change alters other view controller behaviors associated with that child. For example, modal presentations behave differently in a horizontally compact versus horizontally regular environment. You might also make such a change to force the same set of traits on the child view controller regardless of the actual trait environment.
Availability
Available in iOS 8.0 and later.
-
Retrieves the trait collection for a child view controller.
Declaration
Swift
func overrideTraitCollectionForChildViewController(_childViewController: UIViewController) -> UITraitCollection?Objective-C
- (UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewControllerParameters
childViewControllerThe view controller who’s trait collection is to be returned.
Return Value
The trait collection for the designated view controller.
Discussion
Use this method to retrieve the trait collection for a child view controller. You can then modify the trait collection for the designated child view controller and set it using the
setOverrideTraitCollection:forChildViewController:method.Availability
Available in iOS 8.0 and later.
-
Called just before the view controller is added or removed from a container view controller.
Declaration
Swift
func willMoveToParentViewController(_parent: UIViewController?)Objective-C
- (void)willMoveToParentViewController:(UIViewController *)parentParameters
parentThe parent view controller, or
nilif there is no parent.Discussion
Your view controller can override this method when it needs to know that it has been added to a container.
If you are implementing your own container view controller, it must call the
willMoveToParentViewController:method of the child view controller before calling theremoveFromParentViewControllermethod, passing in a parent value ofnil.When your custom container calls the
addChildViewController:method, it automatically calls thewillMoveToParentViewController:method of the view controller to be added as a child before adding it.Availability
Available in iOS 5.0 and later.
See Also
-
Called after the view controller is added or removed from a container view controller.
Declaration
Swift
func didMoveToParentViewController(_parent: UIViewController?)Objective-C
- (void)didMoveToParentViewController:(UIViewController *)parentParameters
parentThe parent view controller, or
nilif there is no parent.Discussion
Your view controller can override this method when it wants to react to being added to a container.
If you are implementing your own container view controller, it must call the
didMoveToParentViewController:method of the child view controller after the transition to the new controller is complete or, if there is no transition, immediately after calling theaddChildViewController:method.The
removeFromParentViewControllermethod automatically calls thedidMoveToParentViewController:method of the child view controller after it removes the child.Availability
Available in iOS 5.0 and later.
See Also
-
The view controller that presented this view controller. (read-only)
Declaration
Swift
var presentingViewController: UIViewController? { get }Objective-C
@property(nonatomic, readonly) UIViewController *presentingViewControllerDiscussion
When you present a view controller modally (either explicitly or implicitly) using the
presentViewController:animated:completion:method, the view controller that was presented has this property set to the view controller that presented it. If the view controller was not presented modally, but one of its ancestors was, this property contains the view controller that presented the ancestor. If neither the current view controller or any of its ancestors were presented modally, the value in this property isnil.Availability
Available in iOS 5.0 and later.
-
The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy. (read-only)
Declaration
Swift
var presentedViewController: UIViewController? { get }Objective-C
@property(nonatomic, readonly) UIViewController *presentedViewControllerDiscussion
When you present a view controller modally (either explicitly or implicitly) using the
presentViewController:animated:completion:method, the view controller that called the method has this property set to the view controller that it presented. If the current view controller did not present another view controller modally, the value in this property isnil.Availability
Available in iOS 5.0 and later.
-
parentViewController parentViewControllerPropertyThe parent view controller of the recipient. (read-only)
Declaration
Swift
weak var parentViewController: UIViewController? { get }Objective-C
@property(nonatomic, weak, readonly) UIViewController *parentViewControllerDiscussion
If the recipient is a child of a container view controller, this property holds the view controller it is contained in. If the recipient has no parent, the value in this property is
nil.Prior to iOS 5.0, if a view did not have a parent view controller and was being presented, the presenting view controller would be returned. On iOS 5, this behavior no longer occurs. Instead, use the
presentingViewControllerproperty to access the presenting view controller.Availability
Available in iOS 2.0 and later.
-
navigationController navigationControllerPropertyThe nearest ancestor in the view controller hierarchy that is a navigation controller. (read-only)
Declaration
Swift
var navigationController: UINavigationController? { get }Objective-C
@property(nonatomic, readonly, strong) UINavigationController *navigationControllerDiscussion
If the view controller or one of its ancestors is a child of a navigation controller, this property contains the owning navigation controller. This property is
nilif the view controller is not embedded inside a navigation controller.Availability
Available in iOS 2.0 and later.
See Also
-
splitViewController splitViewControllerPropertyThe nearest ancestor in the view controller hierarchy that is a split view controller. (read-only)
Declaration
Swift
var splitViewController: UISplitViewController? { get }Objective-C
@property(nonatomic, readonly, strong) UISplitViewController *splitViewControllerDiscussion
If the view controller or one of its ancestors is a child of a split view controller, this property contains the owning split view controller. This property is
nilif the view controller is not embedded inside a split view controller.Availability
Available in iOS 3.2 and later.
See Also
-
tabBarController tabBarControllerPropertyThe nearest ancestor in the view controller hierarchy that is a tab bar controller. (read-only)
Declaration
Swift
var tabBarController: UITabBarController? { get }Objective-C
@property(nonatomic, readonly, strong) UITabBarController *tabBarControllerDiscussion
If the view controller or one of its ancestors is a child of a tab bar controller, this property contains the owning tab bar controller. This property is
nilif the view controller is not embedded inside a tab bar controller.Availability
Available in iOS 2.0 and later.
-
Sent to the view controller when the app receives a memory warning.
Declaration
Swift
func didReceiveMemoryWarning()Objective-C
- (void)didReceiveMemoryWarningDiscussion
Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.
You can override this method to release any additional memory used by your view controller. If you do, your implementation of this method must call the
superimplementation at some point.Availability
Available in iOS 2.0 and later.
-
The identifier that determines whether the view controller supports state restoration.
Declaration
Swift
var restorationIdentifier: String?Objective-C
@property(nonatomic, copy) NSString *restorationIdentifierDiscussion
This property indicates whether the view controller and its contents should be preserved and is used to identify the view controller during the restoration process. The value of this property is
nilby default, which indicates that the view controller should not be saved. Assigning a string object to the property lets the system know that the view controller should be saved. In addition, the contents of the string are your way to identify the purpose of the view controller.During subsequent launches, UIKit asks your app for help in recreating the view controllers that were installed the last time your app ran. When it asks for a specific view controller, UIKit provides your app with this restoration identifier and the restoration identifiers of any parent view controllers in the view controller hierarchy. Your app must use this information to create or locate the appropriate view controller object.
Availability
Available in iOS 6.0 and later.
-
restorationClass restorationClassPropertyThe class responsible for recreating this view controller when restoring the app's state.
Declaration
Swift
var restorationClass: AnyObject.Type?Objective-C
@property(nonatomic, readwrite, assign) Class< UIViewControllerRestoration > restorationClassDiscussion
If a view controller has an associated restoration class, the
viewControllerWithRestorationIdentifierPath:coder:method of that class is called during state restoration. That method is responsible for returning the view controller object that matches the indicated view controller. If you do not specify a restoration class for your view controller, the state restoration engine asks your app delegate to provide the view controller object instead.The restoration class must conform to the
UIViewControllerRestorationprotocol.Availability
Available in iOS 6.0 and later.
-
Encodes state-related information for the view controller.
Declaration
Swift
func encodeRestorableStateWithCoder(_coder: NSCoder)Objective-C
- (void)encodeRestorableStateWithCoder:(NSCoder *)coderParameters
coderThe coder object to use to encode the state of the view controller.
Discussion
Do not call this method directly. The system calls this method during the state preservation process to give your view controller or view-controller subclass a chance to save state-related information.
When deciding what data to save, write the smallest amount of data needed to restore the view controller to its current configuration. The information you save should be data that you could not easily recreate, such as the user’s current selection. You might also save references to any data objects that the view controller was using, but never write the data objects themselves to the coder. Instead, store enough information so that you can retrieve the data objects from your app's main data structures again.
It is strongly recommended that you call
superat some point during your implementation to give parent classes an opportunity to save information. AUIViewControllerobject saves a reference to the presented view controller and to the storyboard (if any) that was used to create the view controller. The view controller also asks the views in its view hierarchy to save any relevant information. However, a view controller does not automatically save references to contained child view controllers. If you are implementing a custom container view controller, you must encode the child view controller objects yourself if you want them to be preserved.Your implementation of this method can encode other restorable objects views, view controllers, and objects that adopt the
UIStateRestoringprotocol, using theencodeObject:forKey:method of the provided coder object. Encoding a restorable object writes that object's restoration identifier to the coder. That identifier is then used during the decode process to locate the new version of the object. If the view or view controller defines its own own version of this method, that method is also called at some point so that the object can encode its own state.For objects that are not restorable, encoding the object writes its data (and not a restoration identifier) to the archive. Such objects must adopt the
NSCodingprotocol. During decoding, the system creates a new object that is initialized with the data from the archive.Availability
Available in iOS 6.0 and later.
See Also
-
Decodes and restores state-related information for the view controller.
Declaration
Swift
func decodeRestorableStateWithCoder(_coder: NSCoder)Objective-C
- (void)decodeRestorableStateWithCoder:(NSCoder *)coderParameters
coderThe coder object to use to decode the state of the view.
Discussion
Do not call this method directly. The system calls this method during the state restoration process so that you can restore your view controller to its previous state.
If your app supports state restoration, override this method for any view controllers for which you also overrode the
encodeRestorableStateWithCoder:method. Your implementation of this method should use any saved state information to restore the view controller to its previous configuration. If yourencodeRestorableStateWithCoder:method calledsuper, this method should similarly callsuperat some point in its implementation.Availability
Available in iOS 6.0 and later.
See Also
-
Called on restored view controllers after other object decoding is complete.
Declaration
Swift
func applicationFinishedRestoringState()Objective-C
- (void)applicationFinishedRestoringStateDiscussion
After other object decoding has completed, the system calls this method. This allows a view controller to complete setup after other state restoration, relying on the system to ensure that the states of all objects from the restoration archive have been decoded.
Availability
Available in iOS 7.0 and later.
-
extensionContext extensionContextPropertyReturns the extension context of the view controller. (read-only)
Declaration
Swift
var extensionContext: NSExtensionContext? { get }Objective-C
@property(nonatomic, readonly, strong) NSExtensionContext *extensionContextDiscussion
The view controller can check this property to see if it participates in an extension request. If no extension context is set for the current view controller, the system walks up the view controller hierarchy to find a parent view controller that has a non
nilextensionContextvalue.Availability
Available in iOS 8.0 and later.
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.
-
Registers a view controller to participate with 3D Touch preview (peek) and commit (pop).
Declaration
Swift
func registerForPreviewingWithDelegate(_delegate: UIViewControllerPreviewingDelegate, sourceViewsourceView: UIView) -> UIViewControllerPreviewingObjective-C
- (id<UIViewControllerPreviewing>)registerForPreviewingWithDelegate:(id<UIViewControllerPreviewingDelegate>)delegatesourceView:(UIView *)sourceViewParameters
delegateThe delegate object mediates the presentation of views from the preview (peek) view controller and the commit (pop) view controller. In practice, these two are typically the same view controller. The delegate performs this mediation through your implementation of the methods of the
UIViewControllerPreviewingDelegateprotocol.sourceViewThe view, in the view hierarchy of the receiver of this method call, that invokes a preview when pressed by the user.
When lightly pressed, the source view remains visually sharp while surrounding content blurs. When pressed more deeply, the system calls the
previewingContext:viewControllerForLocation:method in yourdelegateobject, which presents the preview (peek) view from another view controller.Return Value
A context object for managing the preview. This object conforms to the
UIViewControllerPreviewingprotocol.Discussion
A preview, or peek in end-user terminology, provides additional content related to the view the user pressed (that is, related to the
sourceViewview).Calling this method does three things:
Registers the previewing view controller (the one that receives this method call) to participate with 3D Touch preview and commit
Designates the source view, from the receiver’s view hierarchy, as the view to respond to a forceful touch
Designates a delegate object for mediating the presentation of the preview (peek) and commit (pop) views as a user requests them in turn by pressing more deeply
You can designate more than one source view for a single registered view controller, but you cannot designate a single view as a source view more than once.
The lifetime of this method’s returned context object is managed by the system. If you need to explicitly unregister a view controller, pass its context object to the
unregisterForPreviewingWithContext:method. If you do not unregister a view controller, the system automatically unregisters it when the view controller is deallocated.Availability
Available in iOS 9.0 and later.
-
Unregisters a previously registered view controller identified by its context object.
Declaration
Swift
func unregisterForPreviewingWithContext(_previewing: UIViewControllerPreviewing)Objective-C
- (void)unregisterForPreviewingWithContext:(id<UIViewControllerPreviewing>)previewingParameters
previewingThe context object that was returned when you registered the view controller by calling the
registerForPreviewingWithDelegate:sourceView:method.Discussion
The system calls this method automatically when a 3D Touch-registered view controller is deallocated.
In some circumstances, you must explicitly call this method. This is the case if a registered view controller’s view hierarchy changes state, or if presenting a preview is otherwise no longer possible. In such cases, call this method.
Availability
Available in iOS 9.0 and later.
-
The quick actions displayed when a user swipes upward on a 3D Touch preview.
Declaration
Swift
func previewActionItems() -> [UIPreviewActionItem]Objective-C
- (NSArray<id<UIPreviewActionItem>> *)previewActionItemsReturn Value
An array of preview (peek) quick actions.
Discussion
This property is for use with a preview (peek) view controller which you present in your implementation of the
previewingContext:viewControllerForLocation:delegate method..Implement this method to provide quick actions for such a preview. When the user swipes upward on the preview, the system presents these quick action items in a sheet below the preview.
The default implementation of this method returns an empty array.
For guidance on appropriate items to include as preview quick actions, read the material on 3D Touch in the iOS Technologies chapter of iOS Human Interface Guidelines.
For more information on preview quick actions, see UIPreviewActionItem Protocol Reference and UIPreviewAction Class Reference.
Availability
Available in iOS 9.0 and later.
-
Called when the system needs the view controller to use for determining status bar hidden/unhidden state.
Declaration
Swift
func childViewControllerForStatusBarHidden() -> UIViewController?Objective-C
- (UIViewController *)childViewControllerForStatusBarHiddenReturn Value
The view controller whose status bar hidden/unhidden status should be used. Default return value is
nil.Discussion
If your container view controller derives derives the hidden state of the status bar from one of its child view controllers, implement this method to specify which child view controller you want to control the hidden/unhidden state. If you return
nilor do not override this method, the status bar hidden/unhidden state forselfis used.If you change the return value from this method, call the
setNeedsStatusBarAppearanceUpdatemethod.Availability
Available in iOS 7.0 and later.
-
Called when the system needs the view controller to use for determining status bar style.
Declaration
Swift
func childViewControllerForStatusBarStyle() -> UIViewController?Objective-C
- (UIViewController *)childViewControllerForStatusBarStyleReturn Value
The view controller whose status bar style should be used.
Discussion
If your container view controller derives its status bar style from one of its child view controllers, implement this method and return that child view controller. If you return
nilor do not override this method, the status bar style forselfis used. If the return value from this method changes, call thesetNeedsStatusBarAppearanceUpdatemethod.Availability
Available in iOS 7.0 and later.
-
The preferred status bar style for the view controller.
Declaration
Swift
func preferredStatusBarStyle() -> UIStatusBarStyleObjective-C
- (UIStatusBarStyle)preferredStatusBarStyleReturn Value
A
UIStatusBarStylekey indicating your preferred status bar style for the view controller.Discussion
You can override the preferred status bar style for a view controller by implementing the
childViewControllerForStatusBarStylemethod.If the return value from this method changes, call the
setNeedsStatusBarAppearanceUpdatemethod.Availability
Available in iOS 7.0 and later.
-
Specifies whether the view controller prefers the status bar to be hidden or shown.
Return Value
YEStrueif the status bar should be hidden orNOfalseif it should be shown.Discussion
If you change the return value for this method, call the
setNeedsStatusBarAppearanceUpdatemethod. To specify that a child view controller should control preferred status bar hidden/unhidden state, implement thechildViewControllerForStatusBarHiddenmethod.By default, this method returns
NOfalsewith one exception. For apps linked against iOS 8 or later, this method returnsYEStrueif the view controller is in a vertically compact environment.Availability
Available in iOS 7.0 and later.
See Also
-
Specifies whether a view controller, presented non-fullscreen, takes over control of status bar appearance from the presenting view controller.
Declaration
Swift
var modalPresentationCapturesStatusBarAppearance: BoolObjective-C
@property(nonatomic, assign) BOOL modalPresentationCapturesStatusBarAppearanceDiscussion
The default value of this property is
NOfalse.When you present a view controller by calling the
presentViewController:animated:completion:method, status bar appearance control is transferred from the presenting to the presented view controller only if the presented controller'smodalPresentationStylevalue isUIModalPresentationFullScreen. By setting this property toYEStrue, you specify the presented view controller controls status bar appearance, even though presented non-fullscreen.The system ignores this property’s value for a view controller presented fullscreen.
Availability
Available in iOS 7.0 and later.
-
Specifies the animation style to use for hiding and showing the status bar for the view controller.
Declaration
Swift
func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimationObjective-C
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimationReturn Value
The style of status bar animation to use; one of the constants from the
UIStatusBarAnimationenum. Default value isUIStatusBarAnimationFade.Discussion
This property comes into play only when you actively change the status bar’s show/hide state by changing the return value of the
prefersStatusBarHiddenmethod.Availability
Available in iOS 7.0 and later.
-
Indicates to the system that the view controller status bar attributes have changed.
Declaration
Swift
func setNeedsStatusBarAppearanceUpdate()Objective-C
- (void)setNeedsStatusBarAppearanceUpdateDiscussion
Call this method if the view controller's status bar attributes, such as hidden/unhidden status or style, change. If you call this method within an animation block, the changes are animated along with the rest of the animation block.
Availability
Available in iOS 7.0 and later.
-
navigationItem navigationItemPropertyThe navigation item used to represent the view controller in a parent's navigation bar. (read-only)
Declaration
Swift
var navigationItem: UINavigationItem { get }Objective-C
@property(nonatomic, readonly, strong) UINavigationItem *navigationItemDiscussion
This is a unique instance of
UINavigationItemcreated to represent the view controller when it is pushed onto a navigation controller. The first time the property is accessed, theUINavigationItemobject is created. Therefore, you should not access this property if you are not using a navigation controller to display the view controller. To ensure the navigation item is configured, you can either override this property and add code to create the bar button items when first accessed or create the items in your view controller's initialization code.Avoid tying the creation of bar button items in your navigation item to the creation of your view controller's view. The navigation item of a view controller may be retrieved independently of the view controller's view. For example, when pushing two view controllers onto a navigation stack, the topmost view controller becomes visible, but the other view controller's navigation item may be retrieved in order to present its back button.
The default behavior is to create a navigation item that displays the view controller's title.
Availability
Available in iOS 2.0 and later.
-
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.
Declaration
Swift
var hidesBottomBarWhenPushed: BoolObjective-C
@property(nonatomic) BOOL hidesBottomBarWhenPushedDiscussion
A view controller added as a child of a navigation controller can display an optional toolbar at the bottom of the screen. The value of this property on the topmost view controller determines whether the toolbar is visible. If the value of this property is
YEStrue, the toolbar is hidden. If the value of this property isNOfalse, the bar is visible.Availability
Available in iOS 2.0 and later.
-
Sets the toolbar items to be displayed along with the view controller.
Declaration
Swift
func setToolbarItems(_toolbarItems: [UIBarButtonItem]?, animatedanimated: Bool)Objective-C
- (void)setToolbarItems:(NSArray<UIBarButtonItem *> *)toolbarItemsanimated:(BOOL)animatedParameters
toolbarItemsThe toolbar items to display in a built-in toolbar.
animatedIf
YEStrue, animate the change of items in the toolbar.Discussion
View controllers that are managed by a navigation controller can use this method to specify toolbar items for the navigation controller's built-in toolbar. You can set the toolbar items for your view controller before your view controller is displayed or after it is already visible.
Availability
Available in iOS 3.0 and later.
-
toolbarItems toolbarItemsPropertyThe toolbar items associated with the view controller.
Declaration
Swift
var toolbarItems: [UIBarButtonItem]?Objective-C
@property(nonatomic, strong) NSArray <__kindof UIBarButtonItem *> *toolbarItemsDiscussion
This property contains an array of
UIBarButtonItemobjects and works in conjunction with aUINavigationControllerobject. If this view controller is embedded inside a navigation controller interface, and the navigation controller displays a toolbar, this property identifies the items to display in that toolbar.You can set the value of this property explicitly or use the
setToolbarItems:animated:method to animate changes to the visible set of toolbar items.Availability
Available in iOS 3.0 and later.
See Also
-
tabBarItem tabBarItemPropertyThe tab bar item that represents the view controller when added to a tab bar controller.
Declaration
Swift
var tabBarItem: UITabBarItem!Objective-C
@property(nonatomic, strong) UITabBarItem *tabBarItemDiscussion
This is a unique instance of
UITabBarItemcreated to represent the view controller when it is a child of a tab bar controller. The first time the property is accessed, theUITabBarItemis created. Therefore, you should not access this property if you are not using a tab bar controller to display the view controller. To ensure the tab bar item is configured, you can either override this property and add code to create the bar button items when first accessed or create the items in your view controller's initialization code.The default value is a tab bar item that displays the view controller's title.
Availability
Available in iOS 2.0 and later.
-
A Boolean value indicating whether the view controller currently allows the user to edit the view contents.
Discussion
If
YEStrue, the view controller currently allows editing; otherwise,NOfalse.If the view is editable and the associated navigation controller contains an edit-done button, then a Done button is displayed; otherwise, an Edit button is displayed. Clicking either button toggles the state of this property. Add an edit-done button by setting the custom left or right view of the navigation item to the value returned by the
editButtonItemmethod. Set theeditingproperty to the initial state of your view. Use thesetEditing:animated:method as an action method to animate the transition of this state if the view is already displayed.Availability
Available in iOS 2.0 and later.
-
Sets whether the view controller shows an editable view.
Declaration
Objective-C
- (void)setEditing:(BOOL)editinganimated:(BOOL)animatedParameters
editingIf
YEStrue, the view controller should display an editable view; otherwise,NOfalse.If
YEStrueand one of the custom views of thenavigationItemproperty is set to the value returned by theeditButtonItemmethod, the associated navigation controller displays a Done button; otherwise, an Edit button.animatedIf
YEStrue, animates the transition; otherwise, does not.Discussion
Subclasses that use an edit-done button must override this method to change their view to an editable state if
editingisYEStrueand a non-editable state if it isNOfalse. This method should invoke super’s implementation before updating its view.Availability
Available in iOS 2.0 and later.
See Also
-
Returns a bar button item that toggles its title and associated state between Edit and Done.
Declaration
Swift
func editButtonItem() -> UIBarButtonItemObjective-C
- (UIBarButtonItem *)editButtonItemDiscussion
If one of the custom views of the
navigationItemproperty is set to the returned object, the associated navigation bar displays an Edit button ifeditingisNOfalseand a Done button ifeditingisYEStrue. The default button action invokes thesetEditing:animated:method.Availability
Available in iOS 2.0 and later.
See Also
-
Associates the specified keyboard shortcut with the view controller.
Declaration
Swift
func addKeyCommand(_keyCommand: UIKeyCommand)Objective-C
- (void)addKeyCommand:(UIKeyCommand *)keyCommandParameters
keyCommandThe key command to add.
Discussion
This method lets you easily add key commands to the view controller without overriding the
keyCommandsproperty. The key commands you add to a view controller are applied to the active responder chain. When the user performs a key command, UIKit searches the responder chain (starting with the first responder) for an object capable of handling the specified action.Availability
Available in iOS 9.0 and later.
See Also
-
Removes the key command from the view controller.
Declaration
Swift
func removeKeyCommand(_keyCommand: UIKeyCommand)Objective-C
- (void)removeKeyCommand:(UIKeyCommand *)keyCommandParameters
keyCommandThe key command to remove.
Discussion
This method lets you easily remove key commands without overriding the
keyCommandsproperty.Availability
Available in iOS 9.0 and later.
See Also
-
canDisplayBannerAds canDisplayBannerAdsPropertyA boolean value that indicates whether the view controller is configured to display banner ads.
Declaration
Swift
var canDisplayBannerAds: BoolObjective-C
@property(nonatomic, assign) BOOL canDisplayBannerAdsDiscussion
Set this value to
YEStrueto enable the display of banner ads in a view controller.Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
See Also
-
originalContentView originalContentViewPropertyThe originally configured content view of the view controller before banner ads were enabled. (read-only)
Declaration
Swift
var originalContentView: UIView! { get }Objective-C
@property(nonatomic, retain, readonly) UIView *originalContentViewDiscussion
Apps that use banner views with a view controller should use this property to access the view controller’s content view.
When a view controller enables banner ads, the system puts the view controller’s content view inside of a new content view that the system manages. This allows the system to dynamically resize the original content view when a banner ad is displayed, as well as managing the display of the banner ad itself. This property provides access to the original content view, rather than the containing view that manages banner ad display.
If banner ad display has not been enabled for a view controller, this property returns the content view.
If banner ad display is enabled and then later disabled for a view controller, the system-managed content view is not removed.
Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
A boolean value that indicates whether the view controller is displaying a full-screen ad. (read-only)
Declaration
Swift
var presentingFullScreenAd: Bool { get }Objective-C
@property(nonatomic, readonly, getter=isPresentingFullScreenAd) BOOL presentingFullScreenAdImport Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
See Also
-
displayingBannerAd displayingBannerAdPropertyA boolean value that indicates whether the view controller is displaying a banner ad. (read-only)
Declaration
Swift
var displayingBannerAd: Bool { get }Objective-C
@property(nonatomic, readonly, getter=isDisplayingBannerAd) BOOL displayingBannerAdImport Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
See Also
-
Prepares the iAd framework to display interstitial ads, which may involve prefetching ad assets.
Declaration
Swift
class func prepareInterstitialAds()Objective-C
+ (void)prepareInterstitialAdsDiscussion
Because displaying an ad involves downloading ad assets over the network, in can sometimes be useful to tell the framework to prepare for ad presentation prior to needing to display the first ad. If there is a point in the launch of your app when it would be convenient to prefetch ad assets, you can use this method to trigger one.
If this method is not called, the first fetch will occur when a view controller's
interstitialPresentationPolicyis set to something other thanADInterstitialPresentationPolicyNone.Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
Determines whether interstitials should be presented at all and whether the framework or app should manage the presentation.
Declaration
Swift
var interstitialPresentationPolicy: ADInterstitialPresentationPolicyObjective-C
@property(nonatomic, assign) ADInterstitialPresentationPolicy interstitialPresentationPolicyDiscussion
The default presentation policy for a view controller is
ADInterstitialPresentationPolicyNone. To enable any presentation of interstitial ads the presentation policy must be set toADInterstitialPresentationPolicyAutomaticorADInterstitialPresentationPolicyManual.Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
Asks the framework to display an interstitial ad.
Declaration
Swift
func requestInterstitialAdPresentation() -> BoolObjective-C
- (BOOL)requestInterstitialAdPresentationReturn Value
YEStrueif an interstitial ad will be displayed,NOfalseotherwise.Discussion
This method can be called at any time to request an ad. If an ad is available, the framework presents it immediately. If there is no ad available, nothing happens.
Use this method along with a presentation style of
ADInterstitialPresentationPolicyManualfor a view controller that is on screen for long periods of time and internally manages significant state changes, such as game levels. This allows you to decide precisely when it’s possible for an ad to appear in your app.Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
Returns whether an interstitial ad should be displayed.
Declaration
Swift
var shouldPresentInterstitialAd: Bool { get }Objective-C
@property(readonly, nonatomic) BOOL shouldPresentInterstitialAdReturn Value
YEStrueif the interstitial ad should be displayed now orNOfalseto prevent presentation at this time.Discussion
Implement this method on a custom view controller to allow the view controller to selectively prevent presentation of an interstitial ad. When using the automatic presentation policy, the system invokes this method when the framework is about to present an interstitial ad.
Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
- viewWillUnload(iOS 6.0)Called just before releasing the controller's view from memory.
Deprecation Statement
Views are no longer purged under low-memory conditions and so this method is never called.
Declaration
Objective-C
- (void)viewWillUnloadDiscussion
In iOS 5 and earlier, when a low-memory condition occurred and the current view controller's views were not needed, the system could opt to remove those views from memory. This method was called prior to releasing the actual views so you could perform any cleanup prior to the view being deallocated. For example, you could use this method to remove views as observers of notifications or record the state of the views so it can be reestablished when the views are reloaded.
In iOS 6 and later, clearing references to views is no longer necessary. As a result, any other cleanup related to those views, such as removing them as observers, is also not necessary.
At the time this method is called, the
viewproperty is still valid (it has not yet been set tonil).Availability
Available in iOS 5.0 and later.
Deprecated in iOS 6.0.
-
- viewDidUnload(iOS 6.0)Called when the controller's view is released from memory.
Deprecation Statement
Views are no longer purged under low-memory conditions and so this method is never called.
Declaration
Objective-C
- (void)viewDidUnloadDiscussion
In iOS 5 and earlier, when a low-memory condition occurred and the current view controller's views were not needed, the system could opt to call this method after the view controller's view had been released. This method was your chance to perform any final cleanup. If your view controller stored separate references to the view or its subviews, you could use this method to release those references. You could also use this method to remove references to any objects that you created to support the view but that are no longer needed now that the view is gone. You would not use this method to release user data or any other information that cannot be easily recreated.
In iOS 6 and later, clearing references to views and other objects in your view controller is unnecessary.
At the time this method is called, the
viewproperty isnil.Availability
Available in iOS 3.0 and later.
Deprecated in iOS 6.0.
-
The size of the view controller's view while displayed in a popover.
Deprecation Statement
Use
preferredContentSizeinstead.Declaration
Objective-C
@property(nonatomic, readwrite) CGSize contentSizeForViewInPopoverDiscussion
This property contains the desired size for the view controller when it is displayed in a popover. By default, the width is set to 320 points and the height is set to 1100 points. You can change these values as needed.
The recommended width for popovers is 320 points. If needed, you can return a width value as large as 600 points, but doing so is not recommended.
If the popover controller displaying the view controller sets its
popoverContentSizeproperty, the popover controller overrides the values set in the view controller'scontentSizeForViewInPopoverproperty.Availability
Available in iOS 3.2 and later.
Deprecated in iOS 7.0.
-
- presentModalViewController:animated:(iOS 6.0)Presents a modal view managed by the given view controller to the user.
Deprecation Statement
Use
presentViewController:animated:completion:instead.Declaration
Objective-C
- (void)presentModalViewController:(UIViewController *)modalViewControlleranimated:(BOOL)animatedParameters
modalViewControllerThe view controller that manages the modal view.
animatedIf
YEStrue, animates the view as it's presented; otherwise, does not.Discussion
On iPhone and iPod touch devices, the view of
modalViewControlleris always presented full screen. On iPad, the presentation depends on the value in themodalPresentationStyleproperty.Sets the
modalViewControllerproperty to the specified view controller. Resizes its view and attaches it to the view hierarchy. The view is animated according to the transition style specified in themodalTransitionStyleproperty of the controller in themodalViewControllerparameter.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 6.0.
-
- dismissModalViewControllerAnimated:(iOS 6.0)Dismisses the view controller that was presented by the receiver.
Deprecation Statement
Use
dismissViewControllerAnimated:completion:instead.Declaration
Objective-C
- (void)dismissModalViewControllerAnimated:(BOOL)animatedParameters
animatedIf
YEStrue, this method animates the view as it's dismissed; otherwise, it does not. The style of animation is determined by the value in themodalTransitionStyleproperty of the view controller being dismissed.Discussion
The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, however, it automatically forwards the message to the presenting view controller.
If you present several view controllers in succession, and thus build a stack of presented view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack. When this happens, only the top-most view is dismissed in an animated fashion; any intermediate view controllers are simply removed from the stack. The top-most view is dismissed using its modal transition style, which may differ from the styles used by other view controllers lower in the stack.
If you want to retain a reference to the receiver's presented view controller, get the value in the
modalViewControllerproperty before calling this method.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 6.0.
-
A Boolean value indicating whether the view should underlap the status bar.
Deprecation Statement
Use
edgesForExtendedLayoutandextendedLayoutIncludesOpaqueBarsinstead.Declaration
Objective-C
@property(nonatomic, assign) BOOL wantsFullScreenLayoutDiscussion
When a view controller presents its view, it normally shrinks that view so that its frame does not overlap the device’s status bar. Setting this property to
YEStruecauses the view controller to size its view so that it fills the entire screen, including the area under the status bar. (Of course, for this to happen, the window hosting the view controller must itself be sized to fill the entire screen, including the area underneath the status bar.) You would typically set this property toYEStruein cases where you have a translucent status bar and want your view's content to be visible behind that view.If this property is
YEStrue, the view is not resized in a way that would cause it to underlap a tab bar but is resized to underlap translucent toolbars. Regardless of the value of this property, navigation controllers always allow views to underlap translucent navigation bars.The default value of this property is
NOfalse, which causes the view to be laid out so it does not underlap the status bar.Availability
Available in iOS 3.0 and later.
Deprecated in iOS 7.0.
-
Returns a Boolean value indicating whether the view controller supports the specified orientation.
Deprecation Statement
Override the
supportedInterfaceOrientationsandpreferredInterfaceOrientationForPresentationmethods instead.Declaration
Objective-C
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientationParameters
interfaceOrientationThe orientation of the app's user interface after the rotation. The possible values are described in
UIInterfaceOrientation.Return Value
YEStrueif the view controller auto-rotates its view to the specified orientation; otherwise,NOfalse.Discussion
By default, this method returns
YEStruefor theUIInterfaceOrientationPortraitorientation only. If your view controller supports additional orientations, override this method and returnYEStruefor all orientations it supports.Your implementation of this method should simply return
YEStrueorNOfalsebased on the value in theinterfaceOrientationparameter. Do not attempt to get the value of theinterfaceOrientationproperty or check the orientation value reported by theUIDeviceclass. Your view controller is either capable of supporting a given orientation or it is not.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 6.0.
-
rotatingHeaderView() - rotatingHeaderView(iOS 8.0)Returns the header view to transition during an interface orientation change.
Deprecation Statement
Header views are now animated with the rest of the view.
Return Value
The header view or
nilif there is no header view. If the current view controller is a tab bar controller, this method returns the header view of the view controller in the selected tab. If the current view controller is a navigation controller, this method returns the associated navigation bar.Discussion
In most cases, the header view is the navigation bar and the footer view is the tab bar. If you are implementing this method in a custom view controller that has its own custom header view, you can override this method to return that header view. The view returned from this method should already be part of your view controller's view hierarchy.
You are responsible for adjusting the size and position of the returned view to match the target orientation. You would make such a change in your view controller's rotation methods, such as the
willAnimateRotationToInterfaceOrientation:duration:method.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 8.0.
-
rotatingFooterView() - rotatingFooterView(iOS 8.0)Returns the footer view to transition during an interface orientation change.
Deprecation Statement
Footer views are now animated with the rest of the view.
Return Value
The footer view.
If the view controller is a tab bar controller, returns a view containing the tab bar. If the view controller is a navigation controller, returns the top view controller's footer view. The default implementation returns
nil.Discussion
In most cases, the header view is the navigation bar and the footer view is the tab bar. If you are implementing this method in a custom view controller that has its own custom footer view, you can override this method to return that footer view. The view returned from this method should already be part of your view controller's view hierarchy.
You are responsible for adjusting the size and position of the returned view to match the target orientation. You would make such a change in your view controller's rotation methods, such as the
willAnimateRotationToInterfaceOrientation:duration:method.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 8.0.
-
Convenience property that provides the current orientation of the interface, meaningful only if the view controller is taking up the full screen. (read-only)
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Swift
var interfaceOrientation: UIInterfaceOrientation { get }Objective-C
@property(nonatomic, readonly) UIInterfaceOrientation interfaceOrientationDiscussion
Do not use this property for informing layout decisions.
The possible values for the
interfaceOrientationproperty are described in theUIInterfaceOrientationenum.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 8.0.
-
willRotateToInterfaceOrientation(_:duration:) - willRotateToInterfaceOrientation:duration:(iOS 8.0)Sent to the view controller just before the user interface begins rotating.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Swift
func willRotateToInterfaceOrientation(_toInterfaceOrientation: UIInterfaceOrientation, durationduration: NSTimeInterval)Objective-C
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientationduration:(NSTimeInterval)durationParameters
toInterfaceOrientationThe new orientation for the user interface. The possible values are described in
UIInterfaceOrientation.durationThe duration of the pending rotation, measured in seconds.
Discussion
Subclasses may override this method to perform additional actions immediately prior to the rotation. For example, you might use this method to disable view interactions, stop media playback, or temporarily turn off expensive drawing or live updates. You might also use it to swap the current view for one that reflects the new interface orientation. When this method is called, the
interfaceOrientationproperty still contains the view's original orientation. Your implementation of this method must callsuperat some point during its execution.This method is called regardless of whether your code performs one-step or two-step rotations.
Availability
Available in iOS 2.0 and later.
Deprecated in iOS 8.0.
-
willAnimateRotationToInterfaceOrientation(_:duration:) - willAnimateRotationToInterfaceOrientation:duration:(iOS 8.0)Sent to the view controller before performing a one-step user interface rotation.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Swift
func willAnimateRotationToInterfaceOrientation(_toInterfaceOrientation: UIInterfaceOrientation, durationduration: NSTimeInterval)Objective-C
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientationduration:(NSTimeInterval)durationParameters
interfaceOrientationThe new orientation for the user interface. The possible values are described in
UIInterfaceOrientation.durationThe duration of the pending rotation, measured in seconds.
Discussion
This method is called from within the animation block used to rotate the view. You can override this method and use it to configure additional animations that should occur during the view rotation. For example, you could use it to adjust the zoom level of your content, change the scroller position, or modify other animatable properties of your view.
By the time this method is called, the
interfaceOrientationproperty is already set to the new orientation, and the bounds of the view have been changed. Thus, you can perform any additional layout required by your views in this method.Availability
Available in iOS 3.0 and later.
Deprecated in iOS 8.0.
-
Sent to the view controller after the user interface rotates.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Swift
func didRotateFromInterfaceOrientation(_fromInterfaceOrientation: UIInterfaceOrientation)Objective-C
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientationParameters
fromInterfaceOrientationThe old orientation of the user interface. For possible values, see
UIInterfaceOrientation.Discussion
Subclasses may override this method to perform additional actions immediately after the rotation. For example, you might use this method to reenable view interactions, start media playback again, or turn on expensive drawing or live updates. By the time this method is called, the
interfaceOrientationproperty is already set to the new orientation. Your implementation of this method must callsuperat some point during its execution.This method is called regardless of whether your code performs one-step or two-step rotations.
Availability
Available in iOS 2.0 and later.
Deprecated in iOS 8.0.
-
Sent to the view controller before performing the first half of a user interface rotation.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Objective-C
- (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientationduration:(NSTimeInterval)durationParameters
toInterfaceOrientationThe state of the app's user interface orientation before the rotation. The possible values are described in
UIInterfaceOrientation.durationThe duration of the first half of the pending rotation, measured in seconds.
Discussion
The default implementation of this method does nothing.
This method is called from within the animation block used to rotate the view and slide the header and footer views out. You can override this method and use it to configure additional animations that should occur during the first half of the view rotation. For example, you could use it to adjust the zoom level of your content, change the scroller position, or modify other animatable properties of your view.
At the time this method is called, the
interfaceOrientationproperty is still set to the old orientation.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 5.0.
-
Sent to the view controller after the completion of the first half of the user interface rotation.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Objective-C
- (void)didAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientationParameters
toInterfaceOrientationThe state of the app's user interface orientation after the rotation. The possible values are described in the
UIInterfaceOrientationenum.Discussion
This method is called during two-step rotation animations only. Subclasses can override this method and use it to adjust their views between the first and second half of the animations. This method is called outside of any animation transactions and while any header or footer views are offscreen.
Availability
Available in iOS 2.0 and later.
Deprecated in iOS 5.0.
-
Sent to the view controller before the second half of the user interface rotates.
Deprecation Statement
Use
viewWillTransitionToSize:withTransitionCoordinator:to make interface-based adjustments.Declaration
Objective-C
- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientationduration:(NSTimeInterval)durationParameters
fromInterfaceOrientationThe state of the app's user interface orientation before the rotation. The possible values are described in the
UIInterfaceOrientationenum.durationThe duration of the second half of the pending rotation, measured in seconds.
Discussion
The default implementation of this method does nothing.
This method is called from inside the animation block used to finish the view rotation and slide the header and footer views back into position. You can override this method and use it to configure additional animations that should occur during the second half of the view rotation. For example, you could use it to adjust the zoom level of your content, change the scroller position, or modify other animatable properties of your view.
At the time this method is invoked, the
interfaceOrientationproperty is set to the new orientation.Availability
Available in iOS 2.0 and later.
Deprecated in iOS 5.0.
-
The search display controller associated with the view controller. (read-only)
Deprecation Statement
Use the
UISearchControllerclass to integrate search results.Declaration
Swift
var searchDisplayController: UISearchDisplayController? { get }Objective-C
@property(nonatomic, readonly, strong) UISearchDisplayController *searchDisplayControllerDiscussion
This property reflects the value of the
searchDisplayControlleroutlet that you set in Interface Builder. If you create your search display controller programmatically, this property is set automatically by the search display controller when it is initialized.Availability
Available in iOS 3.0 and later.
Deprecated in iOS 8.0.
-
The controller for the active presented view'that is, the view that is temporarily displayed on top of the view managed by the receiver. (read-only)
Deprecation Statement
Use
presentedViewControllerinstead.Declaration
Objective-C
@property(nonatomic, readonly) UIViewController *modalViewControllerAvailability
Available in iOS 2.0 and later.
Deprecated in iOS 6.0.
-
Returns a Boolean value indicating whether rotation methods are forwarded to child view controllers.
Deprecation Statement
Manually forward calls to the
viewWillTransitionToSize:withTransitionCoordinator:method as needed.Declaration
Swift
func shouldAutomaticallyForwardRotationMethods() -> BoolObjective-C
- (BOOL)shouldAutomaticallyForwardRotationMethodsReturn Value
YEStrueif rotation methods are forwarded orNOfalseif they are not.Discussion
This method is called to determine whether to automatically forward rotation-related containment callbacks to child view controllers.
The default implementation returns
YEStrue. Subclasses of theUIViewControllerclass that implement containment logic may override this method to control how these methods are forwarded. If you override this method and returnNOfalse, you are responsible for forwarding the following methods to child view controllers at the appropriate times:Availability
Available in iOS 6.0 and later.
Deprecated in iOS 8.0.
-
Returns a Boolean value that indicates whether appearance and rotation methods are forwarded.
Deprecation Statement
Manually forward calls to the
viewWillTransitionToSize:withTransitionCoordinator:method as needed.Declaration
Objective-C
- (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllersReturn Value
A Boolean value that indicates whether appearance and rotation methods are forwarded.
Discussion
This method is called to determine whether to automatically forward containment callbacks to the child view controllers.
The default implementation returns
YEStrue. Subclasses of theUIViewControllerclass that implement containment logic may override this method to control how these methods are forwarded. If you override this method and returnNOfalse, you are responsible for forwarding the following methods to child view controllers at the appropriate times:Availability
Available in iOS 5.0 and later.
Deprecated in iOS 6.0.
-
Presents the movie player view controller using the standard movie player transition.
Declaration
Swift
func presentMoviePlayerViewControllerAnimated(_moviePlayerViewController: MPMoviePlayerViewController!)Objective-C
- (void)presentMoviePlayerViewControllerAnimated:(MPMoviePlayerViewController *)moviePlayerViewControllerParameters
moviePlayerViewControllerThe movie player view controller to present.
Import Statement
Objective-C
@import MediaPlayer;Swift
import MediaPlayerAvailability
Available in iOS 3.2 and later.
Deprecated in iOS 9.0.
-
Dismisses a movie player view controller using the standard movie player transition.
Declaration
Swift
func dismissMoviePlayerViewControllerAnimated()Objective-C
- (void)dismissMoviePlayerViewControllerAnimatedDiscussion
If the receiver’s
modalViewControllerproperty does not contain a movie player view controller, this method does nothing.Import Statement
Objective-C
@import MediaPlayer;Swift
import MediaPlayerAvailability
Available in iOS 3.2 and later.
Deprecated in iOS 9.0.
-
Modal presentation styles available when presenting view controllers.
Declaration
Swift
enum UIModalPresentationStyle : Int { case FullScreen case PageSheet case FormSheet case CurrentContext case Custom case OverFullScreen case OverCurrentContext case Popover case None }Objective-C
typedef enum UIModalPresentationStyle : NSInteger { UIModalPresentationFullScreen = 0, UIModalPresentationPageSheet, UIModalPresentationFormSheet, UIModalPresentationCurrentContext, UIModalPresentationCustom, UIModalPresentationOverFullScreen, UIModalPresentationOverCurrentContext, UIModalPresentationPopover, UIModalPresentationNone = -1 } UIModalPresentationStyle;Constants
-
FullScreenUIModalPresentationFullScreenA presentation style in which the presented view covers the screen. The views belonging to the presenting view controller are removed after the presentation completes.
Available in iOS 3.2 and later.
-
PageSheetUIModalPresentationPageSheetIn a horizontally regular environment, a presentation style that partially covers the underlying content. The presented view's width is set to the width of the screen in a portrait orientation and the the height is set to the height of the screen. Any uncovered areas are dimmed to prevent the user from interacting with them. (In portrait orientations, this option is essentially the same as
UIModalPresentationFullScreen.)In a horizontally compact environment, this option behaves the same as
UIModalPresentationFullScreen.Available in iOS 3.2 and later.
-
FormSheetUIModalPresentationFormSheetIn a horizontally regular environment, a presentation style that displays the content centered in the screen. The width and height of the content area are smaller than the screen size and a dimming view is placed underneath the content. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them.
In a horizontally compact environment, this option behaves the same as
UIModalPresentationFullScreen.Available in iOS 3.2 and later.
-
CurrentContextUIModalPresentationCurrentContextA presentation style where the content is displayed over a view controller’s content whose
definesPresentationContextproperty isYEStrue. UIKit may walk up the view controller hierarchy to find a view controller that wants to define the presentation context. The views belonging to the presenting view controller are removed after the presentation completes.When presenting a view controller in a popover, this presentation style is supported only if the transition style is
UIModalTransitionStyleCoverVertical. Attempting to use a different transition style triggers an exception. However, you may use other transition styles (except the partial curl transition) if the parent view controller is not in a popover.Available in iOS 3.2 and later.
-
CustomUIModalPresentationCustomA custom view presentation style that is managed by a custom presentation controller and one or more custom animator objects. All of these objects are provided by the presented view controller’s transitioning delegate, which is an object that conforms to the
UIViewControllerTransitioningDelegateprotocol. Before presenting a view controller using this style, set the view controller’stransitioningDelegateproperty to your custom transitioning delegate.Available in iOS 7.0 and later.
-
OverFullScreenUIModalPresentationOverFullScreenA view presentation style in which the presented view covers the screen. The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.
Available in iOS 8.0 and later.
-
OverCurrentContextUIModalPresentationOverCurrentContextA presentation style where the content is displayed over a view controller’s content whose
definesPresentationContextproperty isYEStrue. UIKit may walk up the view controller hierarchy to find a view controller that wants to define the presentation context. The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.When presenting a view controller in a popover, this presentation style is supported only if the transition style is
UIModalTransitionStyleCoverVertical. Attempting to use a different transition style triggers an exception. However, you may use other transition styles (except the partial curl transition) if the parent view controller is not in a popover.Available in iOS 8.0 and later.
-
PopoverUIModalPresentationPopoverIn a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the
passthroughViewsproperty of the associatedUIPopoverPresentationControllerobject, which you can get from thepopoverPresentationControllerproperty.In a horizontally compact environment, this option behaves the same as
UIModalPresentationFullScreen.Available in iOS 8.0 and later.
-
NoneUIModalPresentationNoneA presentation style that indicates no adaptations should be made. Do not use this style to present a view controller. Instead, return it from the
adaptivePresentationStyleForPresentationController:method of an adaptive delegate when you do not want a presentation controller to adapt the style of an already presented view controller.Available in iOS 7.0 and later.
Import Statement
Objective-C
@import UIKit;Swift
import UIKitAvailability
Available in iOS 3.2 and later.
-
-
Transition styles available when presenting view controllers.
Declaration
Swift
enum UIModalTransitionStyle : Int { case CoverVertical case FlipHorizontal case CrossDissolve case PartialCurl }Objective-C
typedef enum UIModalTransitionStyle : NSInteger { UIModalTransitionStyleCoverVertical = 0, UIModalTransitionStyleFlipHorizontal, UIModalTransitionStyleCrossDissolve, UIModalTransitionStylePartialCurl, } UIModalTransitionStyle;Constants
-
CoverVerticalUIModalTransitionStyleCoverVerticalWhen the view controller is presented, its view slides up from the bottom of the screen. On dismissal, the view slides back down. This is the default transition style.
Available in iOS 3.0 and later.
-
FlipHorizontalUIModalTransitionStyleFlipHorizontalWhen the view controller is presented, the current view initiates a horizontal 3D flip from right-to-left, resulting in the revealing of the new view as if it were on the back of the previous view. On dismissal, the flip occurs from left-to-right, returning to the original view.
Available in iOS 3.0 and later.
-
CrossDissolveUIModalTransitionStyleCrossDissolveWhen the view controller is presented, the current view fades out while the new view fades in at the same time. On dismissal, a similar type of cross-fade is used to return to the original view.
Available in iOS 3.0 and later.
-
PartialCurlUIModalTransitionStylePartialCurlWhen the view controller is presented, one corner of the current view curls up to reveal the presented view underneath. On dismissal, the curled up page unfurls itself back on top of the presented view. A view controller presented using this transition is itself prevented from presenting any additional view controllers.
This transition style is supported only if the parent view controller is presenting a full-screen view and you use the
UIModalPresentationFullScreenmodal presentation style. Attempting to use a different form factor for the parent view or a different presentation style triggers an exception.Available in iOS 3.2 and later.
Import Statement
Objective-C
@import UIKit;Swift
import UIKitAvailability
Available in iOS 3.0 and later.
-
-
Policy options governing how and when interstitial ads may be presented from a view controller.
Declaration
Swift
enum ADInterstitialPresentationPolicy : Int { case None case Automatic case Manual }Objective-C
typedef enum ADInterstitialPresentationPolicy : NSInteger { ADInterstitialPresentationPolicyNone = 0, ADInterstitialPresentationPolicyAutomatic, ADInterstitialPresentationPolicyManual } ADInterstitialPresentationPolicy;Constants
-
NoneADInterstitialPresentationPolicyNoneDefault policy. No interstitial ad is ever presented from the view controller.
Available in iOS 7.0 and later.
-
AutomaticADInterstitialPresentationPolicyAutomaticAutomatic policy. The framework determines when an interstitial ad is presented.
Available in iOS 7.0 and later.
-
ManualADInterstitialPresentationPolicyManualManual policy. The app determines when an interstitial ad should be presented. Use
requestInterstitialAdPresentationto request the presentation of an interstitial ad at an appropriate time.Available in iOS 7.0 and later.
Import Statement
Objective-C
@import iAd;Swift
import iAdAvailability
Available in iOS 7.0 and later.
-
-
Exceptions raised by view controllers.
Declaration
Swift
let UIViewControllerHierarchyInconsistencyException: StringObjective-C
NSString *const UIViewControllerHierarchyInconsistencyExceptionConstants
-
UIViewControllerHierarchyInconsistencyExceptionUIViewControllerHierarchyInconsistencyExceptionRaised if the view controller hierarchy is inconsistent with the view hierarchy.
When a view controller's view is added to the view hierarchy, the system walks up the view hierarchy to find the first parent view that has a view controller. That view controller must be the parent of the view controller whose view is being added. Otherwise, this exception is raised. This consistency check is also performed when a view controller is added as a child by calling the
addChildViewController:method.It is also allowed for a view controller that has no parent to add its view to the view hierarchy. This is generally not recommended, but is useful in some special cases.
Available in iOS 5.0 and later.
-
-
UIViewControllerShowDetailTargetDidChangeNotification UIViewControllerShowDetailTargetDidChangeNotificationPosted when a split view controller is expanded or collapsed.
When a view controller is using
showViewController:sender:orshowDetailViewController:sender:, it may need to know when a split view controller higher in the view hierarchy has changed. This notification is sent when a split view controller expands or collapses. The object of this notification is the view controller that caused the change.Declaration
Swift
let UIViewControllerShowDetailTargetDidChangeNotification: StringImport Statement
Objective-C
@import UIKit;Swift
import UIKitAvailability
Available in iOS 8.0 and later.
Copyright © 2016 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2015-10-21
