Ahmed Hisam
Ahmed Hisam

Reputation: 83

How to use different views/screens/xibs in MonoTouch?

I have created a single view ipad application using MonoTouch. I want to create more screens/views for the application. So I added a new ipad view to the current solution. when i do this a xib is only added to the solution (there is no corresponding .cs file that view controllers have). I have designed the xib in IB but i have no clue as to how to add it to the already existing view controller.

I hope i have made myself clear, so can you please tell me how to proceed.

Upvotes: 1

Views: 571

Answers (1)

Mikayla Hutchinson
Mikayla Hutchinson

Reputation: 16153

Simple answer:

In general you will want to have a view controller for each xib. If you use the "iPad View Controller" template, it will create a controller class and a xib file for it to load. However, you can manually add a controller class very easily - or just copy your existing controller class.

The base controller class does the work of loading and managing the xib - you tell it which to use by passing the xib name to the base constructor:

public partial class MyViewController : UIViewController
{
    public MyViewController () : base ("MyXibName", null)
    ...

Advanced answer:

A "nib" is a file containing serialized UI objects. A "xib" is simply the XML representation of a nib. Your xibs will be compiled into nibs when building the app bundle. The API to load a nib directly from the app bundle is:

NSBundle.MainBundle.LoadNib (xibName, owner);

The name of the xib is its bundle resource ID - the filename but without the extension.

This will load the nib, deserialize all the objects in it and and connect all their outlets to the owner object. This is what you see as the "File's Owner" object in Interface Builder. You can set its type in IB, then connect objects to its outlets and actions. Technically the type of the owner object you use at runtime doesn't actually matter as long as it has the same named outlets and actions that the objects in the xib connect to, and the types of those are compatible.

You have a lot of flexibility with nibs and owner objects at runtime. For example:

  • A view controller could load different nibs depending on the device type by passing different nib names to the base constructor. This is useful for universal app (iPhone+iPad).
  • A nib could contain many UIViews and connect them to multiple outlets on its owner, or a single controller could explicitly load and own several nibs, if you don't want to have lots of controllers.
  • Different controllers could load the same nib, but load different data into its widgets.
  • You could have a base controller class that has outlets, and many nibs belonging to different controller classes that subclass it could connect to those outlets.

Upvotes: 1

Related Questions