UIKit.UIViewController Class
Base class for classes that manage the interaction between Model classes and View classes

See Also: UIViewController Members

Syntax

[Foundation.Register("UIViewController", true)]
public class UIViewController : UIResponder, Foundation.INSCoding, IUIContentContainer, IUITraitEnvironment, IEnumerable, IDisposable

See Also

TransitionCoordinator_UIViewController

Remarks

The UIKit.UIViewController class is the base class of the View Controller hierarchy. View Controllers manage UIKit.UIViews and other UIKit.UIViewControllers. An iOS application has a single window, but many screens, each of which may contain several UIKit.UIViews. Managing those screens is complex and requires responding to both user input and changes in the model (problem domain). This management and coordination is the job of the UIKit.UIViewController.

A UIKit.UIViewController has 3 major responsibilities:

iOS provides a number of standard view controllers such as UIKit.UINavigationController, UIKit.UITabBarController, and UIKit.UIPageViewController. In general, the application developer should prefer to use standard view controllers to create the overall display structure. Using standard view controllers provides consistent, standard behavior and makes it easier for the app to conform to the iOS Human Interface Guidelines.

Additionally, the application developer generally needs to implement one or more “Content View Controllers”. These are often derived directly from UIKit.UIViewController or UIKit.UITableViewController. Content View Controllers are where the application developer writes the custom code to satisfy the UIKit.UIViewControllers responsibilities described previously. In applications that take advantage of Xamarin Studio’s Code Behind facilities for Apple’s Interface Builder, much of this custom code will be automatically generated by Xamarin Studio. Applications written using Dialog do not generally need a custom-written Content View Controller, but may use one for architectural consistency.

A single View Controller may have many views and subcontrollers, but typically a single View Controller will have a single root view and be primarily concerned with controlling that one view or it will be primarily concerned with maintaining a collection of subcontrollers. In the following example, taken from the “Hello World iPhone” sample, a Content View Controller of type HelloWorld_iPhoneViewController is instantiated and set to be the UIWindow.RootViewController for the application’s window:

C# Example

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
       // create a new window instance based on the screen size
       window = new UIWindow (UIScreen.MainScreen.Bounds);
          
       viewController = new HelloWorld_iPhoneViewController ("HelloWorld_iPhoneViewController", null);
       window.RootViewController = viewController;
       window.MakeKeyAndVisible ();
          
       return true;
}

By contrast, the following code taken from the "iOS Standard Controls" sample demonstrates how a UIKit.UITableViewController uses an application-defined NavItemGroup to manage a series of other UIKit.UIViewControllers. In this code, the second parameter to the NavItem constructor is the specific UIKit.UIViewController subtype desired when that item is selected in the table:

C# Example

navGroup = new NavItemGroup ("Toolbars");
navItems.Add (navGroup);
navGroup.Items.Add (new NavItem ("Toolbar 1", "", typeof(Toolbar.Toolbar1_iPhone)));
navGroup.Items.Add (new NavItem ("Programmatic Toolbar", "", typeof(Toolbar.ProgrammaticToolbar_Controller)));
navGroup.Items.Add (new NavItem ("Toolbar Items", "", typeof(Toolbar.ToolbarItems)));
  
// create a table source from our nav items
tableSource = new NavItemTableSource (this.NavigationController, navItems);
  
// set the source on the table to our data source
base.TableView.Source = tableSource;

UIViewController and the MVC Architecture

The following illustration shows the classic relationship between Model, View, and Controller classes. The arrows indicate dependencies: the View depends on the Model class to provide data, the Controller depends on the Model class for information about what to display and depends on the View class to do the drawing. This diagram is idealized: there would be several classes in the Model, several Views, UIKit.UIView can actually use UIResponder.NextResponder to determine their UIKit.UIViewController, etc.

UIViewController, Interface Builder, Storyboards, and Nib files

XCode, Apple’s IDE, contains Interface Builder (“IB”), a tool that allows user interfaces to be created interactively and saved as “Nib” files (these are saved in XML format with the “.xib” extension). Xamarin Studio generates Code Behind classes for nib files and generally these will be subclasses of UIKit.UIViewController. Starting with iOS 5, application developers can use “Storyboards” to visually specify navigation amongst individual UIKit.UIViewControllers. For more on Storyboards, see Introduction to Storyboards.

Universal applications

Xamarin Studio fully supports universal applications that use a single UIKit.UIViewController to control multiple UIKit.UIViews customized for the iPad or the iPhone. As long as the UIKit.UIViews used by the two devices share the same elements, they can share the same Outlets and Actions, as described in the "iPad + Universal (iPhone + iPad) Apps" guide.

It is not necessary for the iPhone and iPad versions to use the same UI elements, however. The application developer may wish to take advantage of the increased screen real-estate and larger set of controls available on the iPad. In such cases, the application developer should create separate UIKit.UIViewControllers and load them appropriatel using code similar to the following, again taken from the “iPad + Universal (iPhone + iPad) Apps“ guide. The choice of the UIKit.UIViewController to be loaded is determined at runtime based on a call to UIKit.UIDevice.CurrentDevice.UserInterfaceIdiom.

C# Example

if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) {
    homeScreen = new Screens.HomeScreen_iPhone();
} else {
    homeScreen = new Screens.HomeScreen_iPad();
}
window.RootViewController = homeScreen;

State Restoration

If you want to provide state restoration in your class, you need to manually add a method with the following signature to your class:

C# Example

[Adopts ("UIViewControllerRestoration")]
class MyUIViewController : UIViewController {

 [Export ("viewControllerWithRestorationIdentifierPath:")]
 static UIViewController FromIdentifierPath (string [] identifierComponents, NSCoder coder)
 {
    var sb = (UIStoryboard) coder.DecodeObject (UIStateRestoration.ViewControllerStoryboardKey);
    if (sb != null){
       var vc = (MyUIViewController) sb.InstantiateViewController ("MyViewController");
       vc.RestorationIdentifier = identifierComponents [identifierComponents.Length-1];
       vc.RestorationClass = Class.GetHandle (typeof (MyViewController));
    }
 }
}

UIViewController Subclasses

ClassUse-caseExample Image
UIKit.UIActivityViewControllerChoose from a set of possible activities

UIKit.UIPageViewControllerPresents content view controllers as a series of pages

UIKit.UINavigationControllerPresents content view controllers one at a time, with a header and optional toolbar

UIKit.UIImagePickerControllerA standard UIKit.UINavigationController for selecting and taking photographs.

UIKit.UIVideoEditorControllerA standard UIKit.UINavigationController for reviewing and editing video and audio files.

UIKit.UITabBarControllerTop-level controller that presents view controllers one at a time, selected by a toolbar along the bottom of the screen.

UIKit.UIReferenceLibraryViewControllerA standard view controller that presents a term and it's dictionary definition.

UIKit.UISplitViewControllerAn iPad-only view controller that presents side-by-side view controllers.

UIKit.UICollectionViewControllerEfficiently displays a large number of cells, arranged in a flexible manner.

UIKit.UITableViewControllerEfficiently displays a large number of cells, arranged vertically.

Adaptive Layout and Rotation

Starting with iOS 8 a series of idioms were introduced into iOS 8 to assist developers in creating applications and UIViewControllers that would work with different form factors, like both iPhone and iPad.

This replaces the pre-iOS8 design that focused on supporting two different form factors (iPhone or iPad) in a particular orientation as well as supporting the transitions from one interface orientation to the other.

New applications should take a number of variables into consideration when laying out the elements on their UI. These include the available size in the canvas, UserInterfaceIdiom (iPad or iPhone), the display scale, and both the vertical and horizontal size classes. The first one is the size of your main view, while the rest are stored in the UIKIt.UIViewController.TraitCollection.

Rotation is now considered a class size change. For example an iPhone held in portrait mode has a regular height and a compact width. When you switch it to landscape, it becomes a compact height and a regular width.

Applications can override UIViewController.TraitCollectionDidChange to react to changes to any of the user interface traits. This method will be invoked during rotations or changes to the user interface that affect the size class of the application.

The UIViewController.ViewWillTransitionToSize method is invoked when rotation takes place.

MVC, MVP, and MVVM

.NET developers will be familiar with Microsoft-promoted architectures that serve the same goal as MVC. Both Model-View-Presenter (MVP) and Model-View-ViewModel (MVVM) strive to maintain the separation between Model classes and display classes. Developers familiar with MVP will be used to Model data flowing through a coordinating Presenter object towards the View rather than MVC’s model in which Views directly subscribe to Model events. It is possible to do an MVP architecture in iOS by increasing the responsibilities of a UIKit.UIViewController. The defining characteristic of MVVM is the use of databinding to ensure that View objects are reactive. iOS controls do not support databinding so MVVM is not possible. MVVM developers will be used to more of a "firewall" between View and Model objects than is available in MVC. MVVM developers should remind themselves to ensure their View objects are as reactive as possible and are not reaching in to the Model for data or taking over Controller responsibilities.

UIViewController and Dialog

Dialog (“MT.D”) allows complex UIs to be rapidly built using declarative statements. As opposed to applications built using Apple’s Interface Builder, most MT.D applications use the predefined Dialog.DialogViewController and do not create their own subclass of UIKit.UIViewController. For more information, refer to the Dialog namespace documentation and the article Introduction to Dialog.

Related content

Requirements

Namespace: UIKit
Assembly: Xamarin.iOS (in Xamarin.iOS.dll)
Assembly Versions: 0.0.0.0