Brian Long Consultancy & Training Services
Ltd.
February 2012
Accompanying source files available through this download link
Note: This introductory tutorial was written for MonoTouch v5.x, as developed and sold by Xamarin. Various aspects make it inappropriate as a resource for earlier versions of MonoTouch, for which you can use this earlier tutorial.
This article will give you an introduction to the process of developing an iPhone application using C# on an Apple Mac in the MonoDevelop IDE with the MonoTouch SDK. With Xamarin's MonoTouch, iPhone development is no longer confined to Objective-C developers using Xcode. It is now opened up to Mono developers using C#.
There is also a much more in-depth and lengthy article that goes into detail on many subjects involved with developing C# applications using MonoTouch available here.
To play along you need a few bits and pieces, which I’ll briefly list:
Note that to actually deploy to an iPhone (or iPad or iPod Touch) you'll need a full version of MonoTouch, which costs $399 and includes a year's worth of updates. You will also need to register with Apple's iPhone Developer Program, which costs $99 per year. To build apps and test them out on the iPhone Simulator costs nothing, assuming you have a Mac.
To show the general idea we’ll build a simple application mimicking a common utility application type: the torch.
In MonoDevelop choose File, New, Solution... and from the C#, MonoTouch, iPhone category choose a Single View Application project. Give it a name of Torch and press OK.
This creates a solution file containing a single project with a number of files. The important files all represent the single main window:
Each window/screen you add to the project typically has a set of files similar to this.
This torch utility will have a button on the window (or view) that will ask you to confirm that you want to turn the ‘torch’ on. Assuming you accept the offer it will switch to another view that is pure white, using the illumination of the screen to act as the ‘torch’. Touching the torch screen will ‘turn off the torch’ and return you to the main screen.
To design the UI double-click the .xib file (referred to as a nib file for historical reasons) in the Solution window and this will load it into Xcode's Interface Builder and look something like this:
What we see here is:
1
).
You can toggle the Navigator view using View, Navigators, Hide/Show Navigator
(or
0
).^3
(that’s
Ctrl-Option-Command-3
or Ctrl-Alt-Apple-3
or Ctrl-Alt-Cmd-3
depending on what's written on your keyboard). You edit the attributes of the
selected object using the Attributes Inspector, which you can access by
selecting View, Utilities, Show Attributes Inspector or press
4
.
In the next screenshot I've hidden the Navigator, shown the Document
Outline and shows the Attributes Inspector and the Object Library. You'll notice
that the Inspectors and Library views appear in the same Utilities window,
Inspector at the top and Library at the bottom. You can hide the Utilities
window at any time by selecting View, Utilities, Hide utilities, or by pressing 0
.
Let’s darken the main application screen by selecting the View in the Document Outline and setting the Background attribute to Black Color.
Now use the Object Library to locate a Round Rect Button (you could type button in the search box at the bottom) and place it on the designer. You can edit the button’s caption using the Title attribute or double-click it. Also add a Navigation Bar and some labels and edit them as desired to make something like the screenshot below.
Note: as well as using the search box, you can also limit the visible controls in the Object Library by using the dropdown list, which defaults to displaying Objects. The button and labels are in the Controls subset and the Navigation Bar is in the Windows & Bars subset.
We’ll set up an event handler for the button back in the code but to do so we need
to add a variable for it in Interface Builder, called an outlet. To do
this we need to see some placeholder code that Xcode works with. It's
Objective-C but don't let that alarm you - MonoTouch will turn it back into C#
as required. We'll see the code if we open the Assistant Editor, which we get by
selecting View, Assistant Editor, Show Assistant Editor (or pressing
).
To add an outlet for the button you Ctrl
+drag from the button to the
code in the Assistant Editor.
When you see an insertion indicator in the file (as seen above) you can release the mouse button and you'll be given a dialog to name the outlet (or choose to make it an action - see later).
Then the outlet is added into the source code file.
Add an outlet for the button called torchButton
.
Save and quit Xcode and we’ll look at the code.
When the application has loaded up the UI for the main
view, TorchControllerView
, its ViewDidLoad()
method executes. In here we’ll set up
the button event handler. The event that fires when the user touches the button
and then releases is TouchUpInside
.
MonoDevelop is helpful here in that it can set up the syntax for an event handler for you, and you get to choose between a lambda expression, regular delegate method, which it will name and implement for you, or an anonymous delegate, with or without parameters. The screenshot below is taken after typing the line you see - the completion list pops up automatically. In this case, choose the first (paramterless) anonymous delegate option.
The code in ViewDidLoad()
now looks like:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
torchButton.TouchUpInside += delegate {
};
}
Before we can write the code in the event handler we need the torch bulb screen. Choose File, New, File... and from the MonoTouch category select iPhone View Controller and call it BulbViewController. This adds another set of files, defining a view that will go in the window, as well as the view controller.
This time we don’t need to do anything to the UI this time – the goal is to have an empty white screen, which helpfully is how this view starts off.
The event handler we were working on in TorchViewController.cs can now be coded, in conjunction with a new variable declared in the class:
private BulbViewController bulbController;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
torchButton.TouchUpInside += delegate {
if (bulbController == null)
bulbController = new BulbViewController ();
View.AddSubview (bulbController.View);
};
}
Now we need a little code in the torch
bulb class. The main code file for the bulb
view is BulbViewController.cs. In order to maximize the screen space used by the
white torchlight this class should remove the iPhone status bar when it is displayed
and restore it when closed. Cue the ViewDidAppear()
and ViewDidDisappear()
virtual methods.
Again MonoDevelop is helpful with overriding methods. In the class definition type
the word override
and a space and the Code Completion list pops up.
You can then select the method to override, maybe honing in on it by typing the
first couple of characters of the target method name. Select the method you want
and it will insert the method declaration with correct signature, override and visibility
directives.
Implement the methods as:
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
UIApplication.SharedApplication.StatusBarHidden = true;
}
public override void ViewDidDisappear (bool animated)
{
UIApplication.SharedApplication.StatusBarHidden = false;
base.ViewDidDisappear (animated);
}
Finally we need to respond to the user touching this view and we can do this with
another virtual method TouchesBegan()
.
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
View.RemoveFromSuperview ();
}
This removes the torch view and so returns to the main screen.
This will work acceptably, however we haven’t yet added in the user confirmation
step. This can be done by invoking a UIAlertView
from the button's
TouchUpInside
handler back in TorchViewController.cs. The alert view is set up with
the required title, message buttons (Yes and No) and a callback.
When you display the alert view the UI thread does not block but instead returns
immediately. The callback you pass in will be set to be the alert view’s Clicked
event handler and will run when the user presses a button to dismiss the alert.
In this case if the user presses Yes another alert will be displayed announcing
the status – the torch will be turned on. Of course if they press No, then
we shall do nothing.
It may be the case that excessive confirmations and messages can be annoying to
the user, but at least this gives us a chance to see how to implement them for when
they are needed. Again, when the second alert is displayed the UI thread will continue
onwards and turn the torch on immediately before the alert is dismissed. To delay
the torch screen until this status alert goes away we can attach an event handler
to the Dismissed
event.
private void TorchLaunch (object sender, UIButtonEventArgs e)
{
if (bulbController == null)
bulbController = new BulbViewController ();
View.AddSubview (bulbController.View);
}
private void TorchLaunchConfirm (object sender, UIButtonEventArgs e)
{
if (e.ButtonIndex == 1)
InfoAlert ("Information", "Torch is being turned on...", TorchLaunch);
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
torchButton.TouchUpInside += delegate {
ConfirmAlert ("Confirmation", "Are you sure you want\nto turn on the torch?", TorchLaunchConfirm);
};
}
InfoAlert()
and ConfirmAlert()
are (rather similar looking)
helper routines that look like this:
private void InfoAlert (string title, string message, EventHandler<UIButtonEventArgs> callback)
{
UIAlertView av = new UIAlertView (title, message, null, "OK");
av.Dismissed += callback;
av.Show ();
}
private void ConfirmAlert (string title, string message, EventHandler<UIButtonEventArgs> callback)
{
UIAlertView av = new UIAlertView (title, message, null, "No", "Yes");
av.Clicked += callback;
av.Show ();
}
And now we have our working torch application for the iPhone!
If you wish to make any comments on this article, your best options are to comment on the blog post that announced it, use the Contact Me form or email me at .
If you find this article useful please consider making a Paypal donation. It will be appreciated however big or small it might be and will encourage Brian to continue researching and writing about interesting topics in the future.
Or if you have some idle time, maybe you could click on some of these ads and see what interesting sites you are taken to.
Brian Long has spent the last 1.6 decades as a trainer, trouble-shooter and mentor focusing on the Delphi, C# and C++ languages, and the Win32, .NET and Mono platforms, recently adding iOS and Android onto the list. In his spare time, when not exploring the Chiltern Hills on his mountain-bike or pounding the pavement in his running shoes, Brian has been re-discovering and re-enjoying the idiosyncrasies and peccadilloes of Unix-based operating systems. Besides writing a Pascal problem-solving book in the mid-90s he has contributed chapters to several books, written countless magazine articles, spoken at many international developer conferences and acted as occasional Technical Editor for Sybex. Brian has a number of online articles that can be found at http://blong.com and a blog at http://blog.blong.com.
© 2012 Brian Long Consulting and Training Services Ltd. All Rights Reserved.
Go back to the top of this page