.storyboard/.xib Less User Interface Design

Creating a Xamarin.Mac application's UI from C# code

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

This article covers creating a Xamarin.Mac Application's User Interface directly from C# code without using Xcode's Interface Builder with `.storyboard` or `.xib` files.

Contents

This article will cover the following topics in detail:

Overview

When working with C# and .NET in a Xamarin.Mac application, you have access to the same user interface elements and tools that a developer working in in Objective-C and Xcode does. Typically, when creating a Xamarin.Mac application, you'll use Xcode's Interface Builder with .storyboard or .xib files to create and maintain you application's User Interface.

You also have the option of creating some or all of your Xamarin.Mac application's UI directly in C# code. In this article, we'll cover the basics of creating User Interfaces and UI Elements in C# code.

Switching a Window to use Code

When you create a new Xamarin.Mac Cocoa application, you get a standard blank, window by default. This windows is defined in a Main.storyboard (or traditionally a MainWindow.xib) file automatically included in the project. This also includes a ViewController.cs file that manages the app's main view (or again traditionally a MainWindow.cs and a MainWindowController.cs file).

To switch to a Xibless window for an application, do the following:

  1. Open the application that you want to stop using .stroyboard or .xib files to define the User Interface in Xamarin Studio.
  2. In the Solution Explorer, right-click on the Main.storyboard or MainWindow.xib file and select Remove:

  3. From the Remove Dialog, click the Delete button to remove the .storyboard or .xib completely from the project:

Now we'll need to modify the MainWindow.cs file to define the Window's layout and modify the ViewController.cs or MainWindowController.cs file to create an instance of our MainWindow class since we are no longer using the .storyboard or .xib file.

Modern Xamarin.Mac apps that use Storyboards for their User Interface may not automatically include the MainWindow.cs, ViewController.cs or MainWindowController.cs files. As required, simply add a new Empty C# Class to the project (Add > New File... > General > Empty Class) and name it the same as the missing file.

Defining the Window in Code

Next, edit the MainWindow.cs file and make it look like the following:

using System;
using Foundation;
using AppKit;
using CoreGraphics;

namespace MacXibless
{
    public partial class MainWindow : NSWindow
    {
        #region Private Variables
        private int NumberOfTimesClicked = 0;
        #endregion

        #region Computed Properties
        public NSButton ClickMeButton { get; set;}
        public NSTextField ClickMeLabel { get ; set;}
        #endregion

        #region Constructors
        public MainWindow (IntPtr handle) : base (handle)
        {
        }

        [Export ("initWithCoder:")]
        public MainWindow (NSCoder coder) : base (coder)
        {
        }

        public MainWindow(CGRect contentRect, NSWindowStyle aStyle, NSBackingStore bufferingType, bool deferCreation): base (contentRect, aStyle,bufferingType,deferCreation) {
            // Define the User Interface of the Window here
            Title = "Window From Code";

            // Create the content view for the window and make it fill the window
            ContentView = new NSView (Frame);

            // Add UI Elements to window
            ClickMeButton = new NSButton (new CGRect (10, Frame.Height-70, 100, 30)){
                AutoresizingMask = NSViewResizingMask.MinYMargin
            };
            ContentView.AddSubview (ClickMeButton);

            ClickMeLabel = new NSTextField (new CGRect (120, Frame.Height - 65, Frame.Width - 130, 20)) {
                BackgroundColor = NSColor.Clear,
                TextColor = NSColor.Black,
                Editable = false,
                Bezeled = false,
                AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MinYMargin,
                StringValue = "Button has not been clicked yet."
            };
            ContentView.AddSubview (ClickMeLabel);
        }
        #endregion

        #region Override Methods
        public override void AwakeFromNib ()
        {
            base.AwakeFromNib ();

            // Wireup events
            ClickMeButton.Activated += (sender, e) => {
                // Update count
                ClickMeLabel.StringValue = (++NumberOfTimesClicked == 1) ? "Button clicked one time." : string.Format("Button clicked {0} times.",NumberOfTimesClicked);
            };
        }
        #endregion

    }
}

Let's discuss a few of the key elements.

First, we added a few Computed Properties that will act like Outlets (as if the window was created in a .storyboard or .xib file):

public NSButton ClickMeButton { get; set;}
public NSTextField ClickMeLabel { get ; set;}

These will give us access to the UI Elements that we are going to display on the window. Since the window isn't being inflated from a .storyboard or .xib file, we need a way to instantiate it (as we'll see later in the MainWindowController class). That's what this new constructor method does:

public MainWindow(CGRect contentRect, NSWindowStyle aStyle, NSBackingStore bufferingType, bool deferCreation): base (contentRect, aStyle,bufferingType,deferCreation) {
    ...
}

This is where we will design the layout of the Window and place any UI Elements needed to create the required User Interface. Before we can add any UI Elements to a Window, it needs a Content View to contain the elements:

ContentView = new NSView (Frame);

This creates a Content View that will fill the Window. Now we add our first UI Element, an NSButton, to the Window:

ClickMeButton = new NSButton (new CGRect (10, Frame.Height-70, 100, 30)){
    AutoresizingMask = NSViewResizingMask.MinYMargin
};
ContentView.AddSubview (ClickMeButton);

The first thing to note here is that, unlike iOS, macOS uses mathematical notation to define it's Window coordinate system. So the origin point is in the lower left hand corner of the Window, with values increasing right and towards the upper right hand corner of the window. When we create the new NSButton, we take this into account as we define its position and size on screen.

The AutoresizingMask = NSViewResizingMask.MinYMargin property tells the button that we want it to stay in the same location from the top of the Window when the Window is resized vertically. Again, this is required because (0,0) is at the bottom left of the Window.

Finally, the ContentView.AddSubview (ClickMeButton) method adds the NSButton to the Content View so that it will be displayed on screen when the application is run and the Window displayed.

Next a label is added to the window that will display the number of times that the NSButton has been clicked:

ClickMeLabel = new NSTextField (new CGRect (120, Frame.Height - 65, Frame.Width - 130, 20)) {
    BackgroundColor = NSColor.Clear,
    TextColor = NSColor.Black,
    Editable = false,
    Bezeled = false,
    AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MinYMargin,
    StringValue = "Button has not been clicked yet."
};
ContentView.AddSubview (ClickMeLabel);

Since macOS doesn't have a specific Label UI Element, we've added a specially styled, non-editable NSTextField to act as a Label. Just like the button before, the the size and location takes into account that (0,0) is at the bottom left of the Window. The AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.MinYMargin property is using the or operator to combine two NSViewResizingMask features. This will make the label stay in the same location from the top of the Window when the Window is resized vertically and shrink and grow in width as the Window is resized horizontally.

Again, the ContentView.AddSubview (ClickMeLabel) method adds the NSTextField to the Content View so that it will be displayed on screen when the application is run and the Window opened.

Adjusting the Window Controller

Since the design of the MainWindow is no longer being loaded from a .storyboard or .xib file, we'll need to make some adjustments to the Window Controller. Edit the MainWindowController.cs file and make it look like the following:

using System;

using Foundation;
using AppKit;
using CoreGraphics;

namespace MacXibless
{
    public partial class MainWindowController : NSWindowController
    {
        public MainWindowController (IntPtr handle) : base (handle)
        {
        }

        [Export ("initWithCoder:")]
        public MainWindowController (NSCoder coder) : base (coder)
        {
        }

        public MainWindowController () : base ("MainWindow")
        {
            // Construct the window from code here
            CGRect contentRect = new CGRect (0, 0, 1000, 500);
            base.Window = new MainWindow(contentRect, (NSWindowStyle.Titled | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Resizable), NSBackingStore.Buffered, false);


            // Simulate Awaking from Nib
            Window.AwakeFromNib ();
        }

        public override void AwakeFromNib ()
        {
            base.AwakeFromNib ();
        }

        public new MainWindow Window {
            get { return (MainWindow)base.Window; }
        }
    }
}

Let discuss the key elements of this modification.

First, we define a new instance of the MainWindow class and assign it to the base Window Controller's Window property:

CGRect contentRect = new CGRect (0, 0, 1000, 500);
base.Window = new MainWindow(contentRect, (NSWindowStyle.Titled | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Resizable), NSBackingStore.Buffered, false);

We define the location of the Window of screen with a CGRect. Just like the coordinate system of the Window, the screen defines (0,0) as the lower left hand corner. Next, we define the style of the Window by using the Or operator to combine two or more NSWindowStyle features:

... (NSWindowStyle.Titled | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable | NSWindowStyle.Resizable) ...

The following NSWindowStyle features are available:

  • Borderless - The Window will have no border.
  • Titled - The Window will have a title bar.
  • Closable - The Window has a Close Button and can be closed.
  • Miniaturizable - The Window has a Miniaturize Button and can be minimized.
  • Resizable - The Window will have a Resize Button and be resizable.
  • Utility - The Window is a Utility style window (panel).
  • DocModal - If the Window is a Panel, it will be Document Modal instead of System Modal.
  • NonactivatingPanel - If the Window is a Panel, it will not be made the Main Window.
  • TexturedBackground - The Window will have a textured background.
  • Unscaled - The Window will not be scaled.
  • UnifiedTitleAndToolbar - The Window's Title and Toolbar areas will be joined.
  • Hud - The Window will be displayed as a Heads-Up Display Panel.
  • FullScreenWindow - The Window can enter full screen mode.
  • FullSizeContentView - The Window's Content View is behind the Title and Toolbar Area.

The last two properties define the Buffering Type for the window and if drawing of the Window will be deferred. For more information on NSWindows, please see Apple's Introduction to Windows documentation.

Finally, since the Window isn't being inflated from a .storyboard or .xib file, we need to simulate it in our MainWindowController.cs by calling the Windows AwakeFromNib method:

Window.AwakeFromNib ();

This will allow you to code against the Window just like a standard window loaded from a .storyboard or .xib file.

Displaying the Window

With the .storyboard or .xib file removed and the MainWindow.cs and MainWindowController.cs files modified, you'll be using the Window just as you would any normal window that had been created in Xcode's Interface Builder with a .xib file.

The following will create a new instance of the Window and its Controller and display the window on screen:

private MainWindowController mainWindowController;
...

mainWindowController = new MainWindowController ();
mainWindowController.Window.MakeKeyAndOrderFront (this);

At this point, if the application is run and the button clicked a couple of times, the following will be displayed:

Adding a Code Only Window

If we want to add a code only, xibless Window to an existing Xamarin.Mac application, right-click of the Project in the Solution Explorer and select Add > New File... In the New File dialog choose Xamarin.Mac > Cocoa Window with Controller, as illustrated below:

Just like before, we'll delete the default .storyboard or .xib file from the Project (in this case SecondWindow.xib) and follow the steps in the Switching a Window to use Code section above to cover the Window's definition to code.

Adding a UI Element to a Window in Code

Whether a Window was created in code or loaded from a .storyboard or .xib file, there might be times where we want to add a UI Element to a Window from code. For example:

var ClickMeButton = new NSButton (new CGRect (10, 10, 100, 30)){
AutoresizingMask = NSViewResizingMask.MinYMargin
};
MyWindow.ContentView.AddSubview (ClickMeButton);

The above code creates a new NSButton and adds it to the MyWindow Window instance for display. Basically any UI Element that can be defined in Xcode's Interface Builder in a .storyboard or .xib file can be created in code and displayed in a Window.

Defining the Menu Bar in Code

Because of current limitations in Xamarin.Mac, it is not suggested that you create your Xamarin.Mac application's Menu Bar–NSMenuBar–in code but continue to use the Main.storyboard or MainMenu.xib file to define it. That said, you can add and remove Menus and Menu Items in C# code.

For example, edit the AppDelegate.cs file and make the DidFinishLaunching method look like the following:

public override void DidFinishLaunching (NSNotification notification)
{
    mainWindowController = new MainWindowController ();
    mainWindowController.Window.MakeKeyAndOrderFront (this);


    // Create a Status Bar Menu
    NSStatusBar statusBar = NSStatusBar.SystemStatusBar;

    var item = statusBar.CreateStatusItem (NSStatusItemLength.Variable);
    item.Title = "Phrases";
    item.HighlightMode = true;
    item.Menu = new NSMenu ("Phrases");

    var address = new NSMenuItem ("Address");
    address.Activated += (sender, e) => {
        Console.WriteLine("Address Selected");
    };
    item.Menu.AddItem (address);

    var date = new NSMenuItem ("Date");
    date.Activated += (sender, e) => {
        Console.WriteLine("Date Selected");
    };
    item.Menu.AddItem (date);

    var greeting = new NSMenuItem ("Greeting");
    greeting.Activated += (sender, e) => {
        Console.WriteLine("Greetings Selected");
    };
    item.Menu.AddItem (greeting);

    var signature = new NSMenuItem ("Signature");
    signature.Activated += (sender, e) => {
        Console.WriteLine("Signature Selected");
    };
    item.Menu.AddItem (signature);
}

The above creates a Status Bar menu from code and displays it when the application is launched. For more information on working with Menus, please see our Menus documentation.

Summary

This article has taken a detailed look at creating a Xamarin.Mac application's User Interface in C# code as opposed to using Xcode's Interface Builder with .storyboard or .xib files.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.