Android
iOS
 

Add a New View

This recipe shows how to add a new view using the iPhone View template in Xamarin Studio.

Recipe

  • Create a new iPhone project named AddNewViewController using the Single View application.
  • In Xamarin Studio type ⌘N to open the New File dialog. Select iOS > iPhone View, enter the name MyNewView and click New to create the view.

  • Double-click MyNewView.xib in Xamarin Studio’s Solution Pad to open the xib in Xcode.
  • With the View selected, open the Identity Inspector and set the view’s class to MyNewView.

  • Add a label and set it text to something like “This is AddNewView.xib.”
  • Select File’s Owner and set the class to AddNewViewViewController.
  • With File’s Owner selected switch to the Connections Inspector and connect the view outlet to the view in the designer.

  • Close Xcode.
  • Add the following class to the project in Xamarin Studio.
[Register("MyNewView")]
class MyNewView: UIView
    {
        public MyNewView (IntPtr p) : base(p)
        {
        }
    }
  • Add the following method to AddNewViewViewController.
public override void LoadView ()
{
    base.LoadView ();
    
    bool shouldLoadNewView = true;
    if (shouldLoadNewView) {
        NSBundle.MainBundle.LoadNib ("MyNewView", this, null);
    }
}

When the application runs, the view defined in the separate xib is loaded as shown below:

Additional Information

The LoadView method of the view controller defaults to reading the xib file associated with the controller. However, it can also be implemented to load a different view for the controller. In most cases, this is used to load a view defined in code, rather than a xib, but as shown here, it can also be used to conditionally load a view defined in a separate xib.