Mono

Using C# to Develop for iPhone, iPod Touch and iPad

Brian Long Consultancy & Training Services Ltd.
February 2012

Accompanying source files available through this download link

Page selection: Previous  Next

Developing Applications With MonoTouch

For our first foray into iPhone application development, tradition dictates we do a Hello World program. In MonoDevelop choose File, New, Solution… (or press ShiftCommandN) or press the Start New Solution link on the welcome screen.

Here you can see the various MonoTouch project templates available. We’ll start off with a Single View Application, since a Hello World will just have a single screen.

New solution in MonoDevelop

This creates a solution containing a single project made up of various files. As with Visual Studio a solution is a means of managing potentially multiple projects. The file opened up by default after creating the project is AppDelegate.cs containing the AppDelegate class, which represents a delegate for the underlying CocoaTouch Application object and can respond to Application events, such as the FinishedLaunching event that triggers when the app has loaded up and which typically contains initialization code.

New project code in MonoDevelop

Info.plist is a property list file used to set various properties of interest to iOS. We’ll ignore this for now (we'll come back to it later).

One of the other files is Main.cs; this contains the simple Application class whose class method Main is the application’s entry point.

New project code in MonoDevelop

View Controllers

The more interesting file, however, is HelloWorldViewController.cs. We could add the functionality of a simple single-screen app into the app delegate class, but purists might suggest that class is best left to act as a delegate for the CocoaTouch Application object. Typical applications are more likely to use one or more view controllers (UIViewController or a descendant) as delegates for views on the various windows in the application.

New project code in MonoDevelop

CocoaTouch operates with an MVC model and this delegate model crops up regularly, for example with event handlers for UI controls.

Talking of UI controls, we need to set up a UI - a view for the view controller to control. The HelloWorldViewController.xib file represents the UI; when double-clicked it will be opened by Xcode in its Interface Builder pane. Historically, Interface Builder was a separate application but as of Xcode 4 has been integrated into the Xcode environment. You’ll be spending some time with Xcode's Interface Builder pane as you build screens for MonoTouch projects.

Note: Originally, Apple UI files were binary and used a .nib extension. When building iOS applications the UI files are XML and use the .xib extension. It is common for OS X and iOS developers to refer to both .xib and .nib files simply as nib files.

Just before looking at Interface Builder I’ll point out the other source file in the project. HelloWorldViewController.designer.cs is an auto-generated file that contains code necessary to access parts of the UI, referred to as the .xib’s code-behind file. We’ll take a look at it again presently.

Xcode's Interface Builder and the UI

Interface Builder is the UI-designing part of Apple’s Xcode development environment and is where we build the UI design part of the iOS application. Which solution/project template you start with dictates the size of the window you get to design, as the resolutions are different. iPhone and iPod Touch are 320x480 whereas iPad is 1024x768.

Note: iPhone 4 has a higher resolution screen than iPhone 3 at 640x960. That is an increase in pixel resolution but, when measured in points, all iPhones offer a 320x480 resolution. This means you only need to design the UI once and it works on all iPhones.

When your .xib file opens in Xcode you are presented with the bare UI in Xcode's Interface Builder pane. On the left side of the window is the Project Navigator, a hierarchical view of files that constitute the Xcode project you are working on. The Navigator pane can show various Navigator views and defaults to showing the Project Navigator. If you want to retrieve the Project Navigator at any time you can choose View, Navigators, Show Project Navigator (or press Command1).

Note: The Navigator can be toggled off and on using the first of the three View toolbuttons on Xcode's toolbar. It can also be toggled with Command0, which alternates between being the shortcut for View, Navigators, Hide Navigator and View, Navigators, Show Navigator.

On the left edge of the Interface Builder is the Dock, where the View can be seen selected. There are other items you can select in the Dock - File's Owner or First Responder but the View is what we'll be focusing on here.

As you add objects to the View you can use the Document Outline to select them (in cases where they are obscured by other objects). The Document Outline appears when you expand the Dock by using the little triangle button at the bottom (or by choosing Editor, Show Document Outline) and can be collapsed again using the same button (or by choosing Editor, Hide Document Outline). The Document Outline was a separate window (the Document window) when Interface Builder was separate from Xcode. You can see the Document Outline in one of the screenshots further down.

Xcode's Interface Builder

Note: the view designer is sized appropriately for your iOS target device (in this case the window is 320x480). If you look carefully at the screenshot, you’ll see that at the top of the window is a simplistic representation of the iPhone’s status bar. This window is essentially a form designer and will reflect our UI as we build it up by adding controls and views.

To edit your view UI you will need to see the available objects you can add. You can do this by displaying the Object Library in the Utilies window. Either choose View, Utilities, Show Object Library or press ^OptionCommand3 (that’s Ctrl-Option-Command-3 or Ctrl-Alt-Apple-3 or Ctrl-Alt-Cmd-3 depending on what's written on your keyboard). There is a Search box at the bottom of the window that filters the potentially long lists shown by default.

Then to edit an object placed on the view (or the view itself) you'll need the Xcode equivalent of an Object Inspector or Properties Inspector, which is called the Attributes Inspector and is also displayed in the Utilities window. Either choose View, Utilities, Show Attributes Inspector or press OptionCommand4. There are other Inspectors, such as the Connections Inspector, which we'll bump into later.

The UI of this starting app will require two Labels (UILabel controls), a Round Rect Button (UIButton) and a Text Field (UITextField). To find these input controls in the Object Library window use the drop-down control to show only Controls (as opposed to the full library of CocoaTouch and custom objects, which is selected by default). This cuts down the list considerably and so you should be able to find the controls readily – they are all adjacent in the list. Again, you can also use the search box to search for the class name or the description (though that resets the drop down filter to show the whole library once more).

Note: When you select an object in the Object Library you get a balloon help window to give you information about it.

Note: You can toggle the Utilities window on and off using the last of the three View toolbuttons on Xcode's toolbar. It can also be toggled with OptionCommand0, which alternates between being the shortcut for View, Utilities, Hide Utilities and View, Utilities, Show Utilities.

Selecting an object to add to the View

Drag the controls to the view and arrange them as below. You can edit the text in all these controls either by double-clicking the control, or using the Text or Title attributes, as appropriate, in the Attributes Inspector (OptionCommand4). Note that the bottom label needs to be bigger than its default size and be instructed to use centre alignment.

If you prefer dark backgrounds, you can set the text color for the labels and the background color of the window itself. The window attributes also let you set the color of the iPhone’s status bar.

Note: The Status Bar setting is described in Interface Builder as a Simulated Metric, so shows you what it might look like, but won’t have an effect at runtime. To finish the job we need to do it in code, and we will.

The text field will automatically pop up a keyboard when tapped (we shall see later that, whilst the keyboard will automatically pop up, it is down to the programmer to dismiss it) and there are various attributes we can configure in the Attributes Inspector. In this case set it to capitalize words and set the Return Key attribute to Done, which changes the normal Return button on the keyboard to be a Done button instead.

Hello world in Interface Builder

That’s the UI designed, but before leaving Xcode we need to cater for the programming that comes next.

Outlets

The code will need to read from the text field and write to the bottom label (and also, just to prove we can, we’ll be writing to the button as well). In order to access the controls we need to define the variables that will refer to them, which are not created by default. These variables are called outlets and are defined by dragging from the control to an Objective-C header file. Yes, we need to work with an Objective-C header file while using Interface Builder, and when we're done, any changes made to the header file will be reflected to the C# code in our MonoTouch project.

To show the header file for the selected View and then add in outlets we use the Assistant Editor. The middle of the three Editor toolbuttons displays this, as does selecting View, Assistant Editor, Show Assistant Editor (or pressing OptionCommandEnter, which is Option-Command-Enter or Alt-Apple-Enter or Alt-Cmd-Enter depending on what's written on your keyboard's keys).

Assistant Editor

To add an outlet for a control you Ctrl+drag from it (or from its representation in the Document Outline) into the header file and ensure an insertion indicator appears telling you that you can successfully drop it there.

Adding an outlet

When you release the mouse button you can choose whether this is an outlet or action (see later), verify its type and give it a name.

Naming an outlet

Having given it a name and pressed Connect the outlet is added to the header file. Here is the file after all the required outlets have been added:

Outlet added

CocoaTouch Actions and Events

The CocoaTouch controls available in Interface Builder have various events that can be responded to, as you’d probably expect. However when using MonoTouch we have a choice of two ways to set up the event handler. One way requires an outlet to be set up in Interface Builder and then uses normal .NET-style events in the source code. The second way matches the traditional Cocoa programming model and revolves around actions and we’ll look at this approach just now.

An action represents a method that gets implemented in your class but is connected to a control’s event in Interface Builder. You set up an action in Interface Builder in a similar way to defining an outlet - Ctrl+drag from the control whose event should be connected to the action and drop in the header file in the Assistant Editor. This pops up the action/outlet editor so you should choose Action as the connection type and enter the action name.

Adding an action

Now save the Xcode project (CommandS), which saves the nib file and we can switch over to MonoDevelop and get on with the code-writing side of things.

Go back to the top of this page

Go back to start of this article

Previous page

Next page