iOS Development with Xamarin Cookbook

4 (2 reviews total)
By Dimitris Tavlikos
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Development Tools

About this book

This book will provide you with the necessary knowledge and skills to be part of the mobile development era, using C#. Covering a wide range of recipes such as creating a simple application and using device features effectively, it will be your companion to the complete application development cycle.

Starting from installing the necessary tools, you will be guided step-by-step on everything you need to develop an application ready to be deployed. You will learn the best practices for interacting with the device hardware, such as the GPS, compass, and the accelerometer. Furthermore, you will be able to manage multimedia resources such as photos and videos captured with the device camera, and much more!

Publication date:
May 2014


Chapter 1. Development Tools

In this chapter, we will cover:

  • Installing prerequisites

  • Creating an iOS project with Xamarin Studio

  • Interface Builder

  • Creating the UI

  • Accessing the UI with Outlets

  • Adding Actions to controls

  • Compiling an iOS project

  • Debugging our application



One of the most important things professionals care about is the tools that are required to complete their work with. Just like carpenters need a chisel to scrape wood, or photographers need a camera to capture light, we developers need certain tools which we cannot work without.

In this chapter, we will provide information on what IDEs (Integrated Development Environments) and SDKs (Software Development Kits) are needed to develop applications for iOS, Apple's operating system, for the company's mobile devices. We will describe what the role of every tool in the development cycle is, and go through the features that are essential to develop our first application.

The following are the tools needed to develop applications with Xamarin.iOS:

  • An Apple Mac computer running at least the Lion (10.7.*) operating system: The essential programs we need cannot be installed on other computer platforms.


    Xamarin also offers Visual Studio development integration for their products. A Mac computer is still required for compiling, testing, debugging, and distributing the application. More information can be found on Xamarin's website at

  • Latest iOS SDK: To be able to download iOS SDK, a developer must be registered as an Apple developer. iOS SDK, among other things, includes two essential components:

    • Xcode: This is Apple's IDE for developing native applications for iOS and Mac with the Objective-C programming language.

    • iOS Simulator: This is an essential program to debug iOS apps on the computer, without the need of a device. Note that there are many iOS features that do not work on the simulator. Hence, a device is needed if an app uses these features.


    Both the registration and SDK download are free of charge from Apple's developer portal ( If we want to run and debug our apps on the device or distribute them on the App Store, we need to enroll to iOS Developer Program, which requires a subscription fee.

  • Xamarin Installer: Xamarin offers all their necessary tools in one installation bundle. This bundle includes the Xamarin.iOS SDK and Xamarin Studio, the IDE for developing iOS applications with C#. A free registration is required for downloading the Xamarin Installer, and it can be found by clicking on the link

This chapter will also describe how to create our first iPhone project with Xamarin Studio, construct its UI with Xcode, and access the app's user interface from within our code, with the concepts of Outlets and Actions.

Last, but not least, we will learn how to compile our app, the available compilation options we have, and how to debug on the simulator.


Installing prerequisites

This section gives you information on how to download and install the necessary tools to develop with Xamarin.iOS.

Getting ready

We need to download all the necessary components on our computer. The first thing to do is register as an Apple developer on The registration is free and easy, and it provides access to all the necessary development resources. After the registration is confirmed through e-mail, we can login and download the iOS SDK from the address At the time of writing, Xcode's latest version is 5.0.1 and iOS SDK's latest version is 7.0.3.

How to do it...

To prepare our computer for iOS development, we need to download and install the necessary components in the following order:

  • Xcode and iOS SDK: A login to the Mac App Store is required. You can either search for Xcode in the App Store or click on the Download Xcode button in the iOS developer portal's download section. After the download is complete, follow the onscreen instructions to install Xcode. The following screenshot shows Xcode in the Mac App Store:

  • Xamarin Starter Edition: Download and run the Xamarin Starter Edition from Xamarin's website Follow the onscreen instructions to install Xamarin Studio and Xamarin.iOS.


    The Xamarin Starter Edition is free, but there are some restrictions, such as a limit on the maximum app bundle size and no Visual Studio support. It does support, however, deploying to a device and to the App Store. At the time of writing, all recipes shown in this book are fully supported by the Starter Edition, except for the Using WCF services recipe in Chapter 6, Web Services. A Business or Enterprise Edition is needed for WCF support.

How it works...

Now that we have everything ready, let's see what each component is needed for.


Xcode is Apple's IDE for developing applications for both iOS and Mac platforms. It is targeted on the Objective-C programming language, which is the main language to program in with the iOS SDK. Since Xamarin.iOS is an SDK for the C# language, one might ask what we would need it for. Apart from providing various tools for debugging iOS apps, Xcode provides us with the Organizer window. Shown in the following screenshot, we can use it to view a device's console logs, install and manage the necessary provisioning profiles, and even view the device's crash logs. To open the Organizer window, navigate to Window | Organizer on the menu bar, or press Cmd + Shift + 2 on the keyboard.

Interface Builder

The second component is Interface Builder. This is the user interface designer, which was formerly a standalone application. Starting with Xcode 4.0, it is integrated into the IDE. Interface Builder provides all the necessary functionality to construct an application user interface. It is also quite different from what .NET developers are accustomed to.

iOS Simulator

The third component is iOS Simulator. It is exactly what its name suggests: a device simulator that we can use to run our apps on, without the need for an actual device. The most important thing about iOS Simulator is that it has the option of simulating older iOS versions (if they are installed on the computer), both iPhone and iPad interfaces and device orientations. However, the simulator lacks some device features that are dependent on hardware such as the compass or accelerometer. Applications using these features must be tested and debugged on an actual device.

Xamarin.iOS is the SDK that allows .NET developers to develop apps for iOS, using the C# programming language. All APIs available to Objective-C developers are also available to C# developers through Xamarin.iOS. It is not a standalone framework with its own APIs for, say, user interfaces. A Xamarin.iOS programmer can use the same UI elements as an Objective-C programmer, along with the added benefits of C# such as generics, LINQ, and asynchronous programming with async/await.

There's more...

Applications developed with Xamarin.iOS have the same chances of making it to the App Store as all other applications developed with the native Objective-C programming language. This means that if an app does not conform to Apple's strict policy about app acceptance, it will fail, whether is written in Objective-C or C#. The Xamarin.iOS team has done a great job in creating an SDK that leaves the developer to worry only about the design and best practice of the code, and nothing else.

Useful links

The following are useful links that you can go through:


Xamarin Studio has a feature for checking available updates. Whenever a program starts, it checks for updates of Xamarin.iOS. It can be turned off, but this is not suggested since it helps with staying up to date with the latest versions. It can be found under Xamarin Studio | Check for Updates.

See also

  • The Compiling an iOS project and Debugging our application recipes

  • The Preparing our app for the App Store recipe in Chapter 14, Deploying


Creating an iOS project with Xamarin Studio

In this recipe, we will discuss how to create our first iOS project with Xamarin Studio.

Getting ready...

Now that we have all the prerequisites installed, we will discuss how to create our first iOS project with Xamarin Studio.

Start Xamarin Studio. It can be found in the Applications folder. Xamarin Studio's default project location is /Users/{yourusername}/Projects. If it does not exist on the hard disk, it will be created when we create out first project. If you want to change the folder, go to Xamarin Studio | Preferences from the menu bar. Select Load/Save in the pane on the left, enter the preferred location for the projects in the Default Solution location field, and click on OK.

How to do it...

The first thing that is loaded when starting Xamarin Studio is its start page. Perform the following steps to create an iOS project with Xamarin Studio:

  1. Navigate to File | New | Solution... from the menu bar. A window that provides us with the available project options will appear.

  2. In the pane on the left of this window, go to C# | iOS | iPhone. The iPhone project templates will be presented on the middle pane.

  3. Select Single View Application.

  4. Finally, enter MyFirstiOSProject for Solution name and click on OK. The following screenshot displays the New Solution window:

That was it. You just created your first iPhone project. You can build and run it; iOS Simulator will start, with a blank light-gray screen nevertheless.


The project templates may be different from the ones shown in the preceding screenshot.

How it works...

Let's see what goes on behind the scenes.

When Xamarin Studio creates a new iOS project, it creates a series of files. The solution files can be viewed in the Solution pad on the left side of Xamarin Studio window. If the Solution pad is not visible, it can be activated by checking on View | Pads | Solution from the menu bar.

The files shown in the following screenshot are the essential files that form an iPhone project:


MyFirstiOSProjectViewController.xib is the file that contains the view of the application. XIB files are basically XML files with a specific structure that Xcode can read. The files contain information about the user interface, such as the type of controls it contains, their properties, and Outlets.


If MyFirstiPhoneProjectViewController.xib, or any other file with the .xib suffix, is double-clicked, Xamarin Studio automatically opens the file in Xcode's Interface Builder.

When we create a new interface with Interface Builder and save it, it is saved in the XIB format.


MyFirstiOSProjectViewController.cs is the file that implements the view's functionality. These are the contents of the file when it is created:

using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace MyFirstiOSProject
    public class MyFirstiOSProjectViewController : UIViewController
        public MyFirstiOSProjectViewController () : base ("MyFirstiOSProjectViewController", null)

        public override void DidReceiveMemoryWarning ()
            // Releases the view if it doesn't have a superview.base.DidReceiveMemoryWarning ();
            // Release any cached data, images, etc that aren't in use.

        public override void ViewDidLoad ()
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.


Xamarin.iOS was formerly known as MonoTouch. For proper code compatibility, the namespaces have not been renamed.

The code in this file contains the class which corresponds to the view that will be loaded, along with some default method that overrides. These methods are the ones that we will use more frequently when we create view controllers. A brief description of each method is listed as follows:

  • ViewDidLoad: This method is called when the view of the controller is loaded. This is the method we use to initialize any additional component.

  • DidReceiveMemoryWarning: This method is called when the app receives a memory warning. This method is responsible for releasing resources that are not needed at the time.


MyFirstiOSProjectViewController.designer.cs is the file that holds our main window's class information in C# code. Xamarin Studio creates one .designer.cs file for every XIB that is added in a project. The file is autogenerated every time we save a change in our XIB through Interface Builder. This is taken care of by Xamarin Studio so that the changes we make in our interface are reflected right away in our code. We must not make changes to this file directly, since when the corresponding XIB is saved with Interface Builder, they will be lost. Also, if nothing is saved through Interface Builder and if changes are made to it manually, it will most likely result in a compilation error.

These are the contents of the file when a new project is created:

// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
using MonoTouch.Foundation;

namespace MyFirstiOSProject
    [Register ("MyFirstiOSProjectViewController")]
    partial class MyFirstiOSProjectViewController
        void ReleaseDesignerOutlets ()


Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

This file contains the other partial declaration of our MyFirstiOSProjectViewController class. It is decorated with the Register attribute.

The Register attribute is used to expose classes to the underlying Objective-C runtime. The string parameter declares by what name our class will be exposed to the runtime. It can be whatever name we want it to be, but it is a good practice to always set it to our C# class' name. The attribute is used heavily in the internals of Xamarin.iOS, since it is what binds all the native NSObject classes with their C# counterparts.


NSObject is a root class or base class. It is the equivalent of System.Object in the .NET world. The only difference between the two is that all .NET objects inherit from System.Object, but most, not all, Objective-C objects inherit from NSObject in Objective-C. The C# counterparts of all native objects that inherit from NSObject also inherit from its Xamarin.iOS NSObject counterpart.


The AppDelegate.cs file contains the AppDelegate class. The contents of the file are listed below:

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace MyFirstiOSProject
    // The UIApplicationDelegate for the application. This classis responsible for launching the
    // User Interface of the application, as well as listening(and optionally responding) to
    // application events from iOS.
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
        // class-level declarations
        UIWindow window;
        MyFirstiOSProjectViewController viewController;
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        public override bool FinishedLaunching (UIApplication app,NSDictionary options)
            window = new UIWindow (UIScreen.MainScreen.Bounds);
            viewController = new MyFirstiOSProjectViewController ();
            window.RootViewController = viewController;
            window.MakeKeyAndVisible ();
            return true;

The first part is familiar to .NET developers and consists of the appropriate using directives that import the required namespaces to use. Consider the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

The first three using directives allow us to use the specific and familiar namespaces from the .NET world with Xamarin.iOS.


System, System.Collections.Generic, System.Linq: Although the functionality that the three namespaces provide is almost identical to their well-known .NET counterparts, they are included in assemblies specifically created for use with Xamarin.iOS and shipped with it, of course. An assembly compiled with .NET cannot be directly used in a Xamarin.iOS project.

The MonoTouch.Foundation namespace is a wrapper around the native Objective-C Foundation Framework, which contains classes that provide basic functionality. These objects' names share the same NS prefix that is found in the native Foundation Framework. Some examples are NSObject, NSString, NSValue, and so on. Apart from the NS-prefixed objects, the MonoTouch.Foundation namespace contains all of the attributes that are used for binding to native objects, such as the Outlet and Register attributes we saw earlier. The MonoTouch.UIKit namespace is a wrapper around the native Objective-C UIKit Framework. As its name suggests, the namespace contains classes, delegates, and events that provide us with interface functionality. Almost all the objects' names share the same UI prefix. It should be clear at this point that these two namespaces are essential for all Xamarin.iOS apps, and their objects will be used quite frequently.

The class inherits from the UIApplicationDelegate class, qualifying it as our app's delegate object.


The concept of a delegate object in the Objective-C world is somewhat different from delegate in C#. It will be explained in detail in Chapter 2, User Interface – Views.

The AppDelegate class contains two fields and one method:

UIWindow window;MyFirstiOSProjectViewController viewController; 
public override bool FinishedLaunching (UIApplication app, NSDictionary options) {

The UIWindow object defines the main window of our application, while the MyFirstiOSProjectViewController object is the variable that will hold the app's view controller.


An iOS app typically has only one window of type UIWindow. UIWindow is the first control that is displayed when an app starts, and every subsequent view is hierarchically added below it.

The FinishedLaunching method, as its name suggests, is called when the app has completed its initialization process. This is the method where we must present the user interface to the user. The implementation of this method must be lightweight; if it does not return in time from the moment it is called, iOS will terminate the app. This provides faster user interface loading time to the user by preventing developers from performing complex and long-running tasks upon initialization, such as connecting to a web service to receive data. The app parameter is the application's UIApplication object, which is also accessible through the static property UIApplication.SharedApplication. The options parameter may or may not contain information about the way the app was launched. We do not need it for now.

The default implementation of the FinishedLaunching method for this type of project is as follows:

  • The UIWindow object is initialized with the size of the screen as follows:

    window = new UIWindow (UIScreen.MainScreen.Bounds);
  • The view controller is initialized and set as the window's root view controller as follows:

    viewController = new MyFirstiPhoneProjectViewController();
    window.RootViewController = viewController;
    window.MakeKeyAndVisible ();
    return true;

The window is displayed on the screen with the window.MakeKeyAndVisible() call and the method returns. This method must be called inside the FinishedLaunching method, otherwise the app's user interface will not be presented as it should be to the user. Last but not least, the return true line returns the method by marking its execution completion.


Inside the Main.cs file is where the runtime life cycle of the program starts as shown in the following code:

namespace MyFirstiOSProject
    public class Application
        // This is the main entry point of the application.
        static void Main (string[] args)
            // if you want to use a different Application Delegate class from "AppDelegate"
            // you can specify it here.
            UIApplication.Main (args, null, "AppDelegate");

It is much like the following call in a .NET System.Windows.Forms application:

Application.Run(new Form1());

The UIApplication.Main method starts the message loop or run loop that is responsible for dispatching notifications to the app through the AppDelegate class with event handlers that we can override. Event handlers such as FinishedLaunching, ReceiveMemoryWarning, or DidEnterBackground are only some of these notifications. Apart from the notification dispatching mechanism, the UIApplication object holds a list of all UIWindow objects that exist, typically one. An iOS app must have one UIApplication object, or a class that inherits from it, and this object must have a corresponding UIApplicationDelegate object. This is the AppDelegate class implementation we saw earlier.


The Info.plist file is basically the app's settings file. It has a simple structure of properties with values that define various settings for an iOS app, such as the orientations it supports, its icons, supported iOS versions, what devices it can be installed on, and so on. If we double-click on this file in Xamarin Studio, it will open in the embedded editor specifically designed for this file. Our file in a new project looks like the following screenshot:

We can also access Info.plist through the project's options window under iOS Application.

There's more...

Xamarin Studio provides many different project templates for developing iOS apps. Here is a list that describes what each project template is for:

  • Empty project: This is an empty project without any views.

  • Utility application: This is a special type of iOS app that provides one screen for functionality and, in many cases, another one for configuration.

  • Master-detail application: This type of project creates a template that supports navigating through multiple screens. It contains two view controllers.

  • Single view application: This template type is the one we used in this recipe.

  • Tabbed application: This is a template that adds a tab bar controller, which manages two view controllers in a tab-like interface.

  • OpenGL application: This is a template for creating OpenGL-powered applications or games.

These templates are available for the iPhone, iPad, and Universal (both iPhone and iPad) projects. They are also available in Interface Builder's storyboarding app design.


Unless stated, all project templates referring to the iPhone are suitable for the iPod Touch as well.

List of Xamarin.iOS assemblies

Xamarin.iOS-supported assemblies can be found at

See also

  • The Creating the UI and Accessing the UI with Outlets recipes

  • The Adding and customizing views recipe in Chapter 2, User Interface – Views


Interface Builder

In this recipe, we will take a look at Xcode's Interface Builder. Since we cannot use Xcode to write our code, Xamarin Studio provides a transparent way of communicating with Xcode when it comes to user interface files.

How to do it...

Let's take a look at Interface Builder by performing the following steps:

  1. If you have installed the iOS SDK, then you already have Xcode with Interface Builder installed on your computer. Go to Xamarin Studio and open the project MyFirstiOSProject we created earlier.

  2. In the Solution pad on the left, double-click on MyFirstiOSProjectViewController.xib. Xamarin Studio starts Xcode with the file loaded in Interface Builder.

  3. On the top of the Xcode window in the right side of the toolbar, select the appropriate editor and viewing options, as shown in the following screenshot:

  4. The following screenshot demonstrates what Interface Builder looks like with an XIB file open:

How it works...

Now that we have loaded Interface Builder with the view controller of our app, let's familiarize ourselves with it.

The user interface designer is directly connected to an Xcode project. When we add an object, Xcode automatically generates code to reflect the change we made. Xamarin Studio takes care of this for us, so that when we double-click on an XIB file, it automatically creates a temporary Xcode project. This allows us to make the changes we want in the user interface. Therefore, we have nothing more to do than just design the user interface for our app.

Interface Builder is divided into three areas. A brief description of each area is given as follows:

  • Navigator area: In this area, we can see the files included in the Xcode project.

  • Editor area: This area is where we design the user interface. The editor area is divided into two sections. The one on the left is the designer, and the one on the right is the assistant editor. Inside the assistant editor, we see the underlying Objective-C source code file that corresponds to the selected item in the designer. Although we do not need to edit the Objective-C source, we will need the assistant editor later.

  • Utility area: This area contains the inspector and library panes. The inspector pane is where we configure each object, and the library pane is where we find the objects.

There's more...

We saw what an XIB file looks like in Interface Builder, but there is more as far as these files are concerned. We mentioned earlier that XIB files are XML files with appropriate information readable by Interface Builder. The thing is that when a compilation is done in a project, the compiler compiles the XIB file converting it to its binary equivalent, the NIB file. Both XIB and NIB files contain the same information. The only difference between them is that XIB files are in a human-readable form while the NIB files are not. For example, when we compile the project we created, the MyFirstiOSProjectViewController.xib file will become MyFirstiOSProjectViewController.nib in the output folder. Apart from the binary conversion, the compiler also performs a compression on NIB files. So, NIB files will be significantly smaller in size than XIB files.

That's not all about XIB files. The way a developer manages the XIB files in a project is very important in an app's performance and stability. It is better to have many small-sized XIB files, instead of one or two large ones. This is because of the way iOS manages its memory. This can be accomplished by dividing the user interface into many XIB files. It may seem a bit difficult, but as we'll see later in this book, it is actually very easy.

When an app starts, iOS loads the NIB files as a whole in memory, and all the objects in it are instantiated. So, it is a waste of memory to keep objects in NIB files that are not always going to be used. Also, remember that you are developing for a mobile device whose available resources are not a match against that of desktop computers, no matter what its capabilities are.

As of iOS 5, Apple introduced storyboarding, which simplifies user interface design.

More information

You may have noticed that in the Attributes tab of the Inspector pane, there is a section called Simulated Metrics. Options under this section help us see directly what our interface looks like in the designer area with the device's status bar, a toolbar, or a navigation bar. Although these options are saved in the XIB files, they have nothing to do with the actual app at runtime. For example, if we set the Status Bar option to None, it does not mean that our app will start without a status bar.


Status Bar is the bar that is shown on the top portion of the device's screen, which displays certain information to the user, such as the current time, battery status, and carrier name on the iPhone.

See also

  • The Creating the UI, Accessing the UI with Outlets, and Adding Actions to controls recipes

  • The Adding and customizing views recipe in Chapter 2, User Interface – Views

  • The Loading a view with a view controller recipe in Chapter 3, User Interface – View Controllers


Creating the UI

In this recipe, we will learn how to add and manage controls in the user interface.

Getting ready

Let's add a few controls in an interface. Start by creating a new iPhone single view application project in Xamarin Studio. Name the project ButtonInput. When it opens, double-click on ButtonInputViewController.xib in the Solution pad to open it with Interface Builder.

How to do it...

Now that we have a new project, and Interface Builder has opened the ButtonInputViewController.xib file, we'll add some controls to it.

Adding a label

Perform the following steps:

  1. Go to the Library pane and select Objects from the drop-down list, if it is not already selected.

  2. Select the Label object. Drag-and-drop Label onto the gray space of the view in the designer, somewhere in the top half.

  3. Select and resize the Label object from both the left and right sides so that it snaps to the dashed line that will show up when you reach close to the edges of the view.

  4. Again, with the Label object selected, go to the Inspector pane, select the Attributes tab, and in the Layout section, click on the middle alignment button.

Congratulations, you have just added Label in your app's main view!

Adding a button

We will perform similar steps to add a button in our interface, using the following steps:

  1. Again, in the Library pane, in the Objects section, select the Button object. It is next to the Label object. Drag-and-drop it onto the bottom half of the view. Align its center with the center of Label we added earlier.

  2. A dashed line will show up, and the Button object will snap to it when the centers of the two controls are almost aligned.

  3. Resize the Button object to the same width as that of Label. Since Label has a transparent background, and you cannot see how wide it is exactly, you will know when the Button object is of the same width when three dashed lines show up while you are resizing it.

  4. Now, let's add some text to Button. Select it and go to Inspector pane.

  5. In the Attributes tab of the Title field, enter Tap here please!.

  6. After adding the button, save the document by navigating to File | Save in the menu bar. The main view should now look like the following screenshot:

How it works...

As you can see, although some concepts of Interface Builder seem difficult, it is quite easy to use. It also provides a lot of feedback. When we drag objects, guidelines that basically act as snap points for positioning the control properly, appear. Also, when we resize a control, we see its dimensions next to it.

You can also resize and position the controls by modifying the values in the Size tab of the Inspector pane. Another useful feature in the Size tab is Autosizing. Autosizing provides layout options for the controls, and it can be very useful when we want our app to support different device orientations. You can select a control you want, and then click on the lines that are outside or inside of the square on the left in the Autosizing section. The image next to it animates to give you an impression of how the control will behave when the layout changes.

There's more...

Now, let's try running the app on iOS Simulator. Back in Xamarin Studio, select the project configuration Debug if it is not already selected. Depending on the version of iOS SDK you have installed, the following screenshot shows the available options of debugging targets:

Select your preferred target and click on the Run button. When the compilation finishes, iOS Simulator will automatically start and run the app we just created. You can even tap on Button by clicking on it with the mouse, and see it responding. Of course, our app does not have any other functionality right now.

Setting titles on Buttons

Setting the title of a Button or Label can be done by simply double-clicking on it and typing the preferable title. Do it, and watch how Interface Builder behaves to show you what action is to be performed.

See also

  • The Compiling an iOS project and Debugging our application recipes

  • The Receiving user input with buttons recipe in Chapter 2, User Interface – Views


Accessing the UI with Outlets

In this recipe, we will discuss the concept of Outlets and their usage with Xamarin.iOS.

Getting ready

In the previous recipe, we learned how to add controls to form a basic interface for our app. In this recipe, we will discuss how to access and use these controls in our code. Launch Xamarin Studio and open the project ButtonInput we created earlier. Open the project's ButtonInputViewController.xib in Interface Builder by double-clicking on it in the Solution pad.

How to do it...

Perform the following steps to access the UI with Outlets:

  1. In the assistant editor, select the ButtonInputViewController.h file, press the Ctrl key, and drag it from Label to the Objective-C source file, as displayed in the following screenshot:

  2. When you release the cursor, a context window will appear similar to the one in the following screenshot:

  3. In the Name field of the context window, enter labelStatus and click on Connect.

  4. Do the same for Button, and name it buttonTap. Save the Interface Builder document by navigating to File | Save in the menu bar or by pressing Cmd + S on the keyboard.

  5. Back in Xamarin Studio, enter the following code in the ViewDidLoad method of the ButtonInputViewController class:

    // Create and hook a handler to our button's TouchUpInside event
    // through its outlet
    this.buttonTap.TouchUpInside += delegate(object sender, EventArgs e) {
      this.labelStatus.Text = "Button tapped!";

    This code snippet adds a handler to the button's TouchUpInside event. This event is similar to the Clicked event of a Button control in System.Windows.Forms. It also displays the usage of an anonymous method, which just shows how Xamarin.iOS provides C# features to .NET developers.

That was it! Our app is now ready with functional controls. Compile and run it on the simulator. See the label changing its text when you tap on the button.

How it works...

The Outlet mechanism is basically a way of connecting Interface Builder objects with the code. It is necessary since it is the only way we can access user interface objects that we create with Interface Builder. This is how Interface Builder works, and it is not just a Xamarin.iOS workaround. An Outlet of an object provides a variable of this object so that we will be able to use it in a project. Xamarin.iOS makes a developer's life much easier because when we create Outlets in Interface Builder and connect them, Xamarin Studio works in the background by autogenerating code regarding these Outlets. This is what the ButtonInputViewController.designer.cs file has added to provide us access to the controls we created:

MonoTouch.UIKit.UILabel labelStatus { get; set; }

MonoTouch.UIKit.UIButton buttonTap { get; set; }

These are the properties which provide us access to the controls. They are decorated with the Outlet attribute. You can see that the names of the properties are exactly the same names we entered for our Outlets. This is very important since we only have to provide names once for the Outlets, and we do not have to worry about repeating the same naming conventions in different parts of our code. Also, notice that the types of variables of the controls are exactly the same as the types of controls we dragged-and-dropped in our user interface. This information is stored in the XIB file, and Xamarin Studio reads this information accordingly.

There's more...

To remove Outlets, you first have to disconnect them. For example, to remove the buttonTap Outlet, press Ctrl and click on the button. In the panel that will appear, click on the x button next to the Outlet, as shown in the following screenshot. This will disconnect the Outlet.

After this, delete the following code from the Objective-C source file:

@property (retain, nonatomic) IBOutlet UIButton *buttonTap;

When you save the document, the Outlet will be removed from the Xamarin Studio project.

Adding Outlets through code

Another way of adding Outlets is to create a property in your C# class and decorate it with the Outlet attribute:

UIButton ButtonTap { get;	set; }

When you open the XIB file in Interface Builder, the Outlet will be added to the user interface. However, you would still have to connect it to the corresponding control. The easiest way to do this is to press Ctrl, click on the control the Outlet corresponds to, and click-and-drag from New Referencing Outlet to the File's Owner object on the left of the designer area, as shown in the following screenshot:

When you release the cursor, select the ButtonTap Outlet from the small context menu that will appear.


Note that it is Xamarin Studio that monitors for changes made in Interface Builder, and not the other way around. When making changes in the Xamarin project, make sure to always open the XIB file from Xamarin Studio.

See also

  • The Interface Builder, Creating the UI, and Adding Actions to controls recipes

  • The Adding and customizing views recipe in Chapter 2, User Interface – Views


Adding Actions to controls

In this recipe, we discuss the concept of Actions and their usage with Xamarin.iOS.

Getting ready

In this recipe, we will discuss how to use Actions with the controls of the user interface.

  1. Create a new iPhone single view application project in Xamarin Studio and name it ButtonInputAction.

  2. Open ButtonInputActionViewController.xib in Interface Builder, and add the same controls, Outlets, and connections as the ones from the project ButtonInput from the previous recipe. Do not add any code in the project for now.

How to do it...

Adding Actions to interface objects is similar to adding Outlets, as follows:

  1. In Interface Builder, press Ctrl and drag from the button to the source code file.

  2. In the context window that will be shown, change the Connection field from Outlet to Action.

  3. Enter OnButtonTap in the Name field, and select Touch Up Inside in the Event field, if it is not already selected.

  4. Click on the Connect button and save the document.

  5. In the ButtonInputActionViewController class, add the following method:

    partial void OnButtonTap(NSObject sender)
      this.labelStatus.Text = "Button tapped!";

The app is ready! Compile and run it in the simulator. Tap on the button and see the text in the label change, just like in the previous app we created.

How it works...

Actions in Objective-C are the equivalent of control events in C#. They are responsible for delivering notification signals of various objects. In this example, instead of hooking up a handler on the TouchUpInside event of the button, we have added an action for it. As you may already have noticed, the method we added to act as a handler for the action was declared as partial; this is because Xamarin Studio already declared a partial method declaration for us. This is the code that was produced when we saved the document in Interface Builder:

[Action ("OnButtonTap:")]
partial void OnButtonTap (MonoTouch.Foundation.NSObject sender);

The partial declaration of the method is marked with the Action attribute. This is another attribute from the MonoTouch.Foundation namespace that allows us to expose methods as Objective-C Actions. You see that the string parameter passed in the attribute is exactly the same as the action name we entered in Interface Builder, with only an appended colon (:) to it.


Colons in Objective-C indicate the presence of parameters. For example, doSomething is different from doSomething;. The difference is that the first does not accept any parameters, and the second accepts one parameter.

The colon at the end of the action name indicates that there is one parameter, in this case, the parameter MonoTouch.Foundation.NSObject sender. This is what our app looks like when we have tapped on the button in the simulator:

There's more...

The example in the preceding section was created just to show how to implement actions in Xamarin.iOS projects. Replacing an event with an action is basically at the discretion of the developer.

See also

  • The Interface Builder, Creating the UI, and Accessing the UI with Outlets recipes


Compiling an iOS project

In this recipe, we will discuss how to compile a project with Xamarin.iOS.

Getting ready

Xamarin Studio provides many different options for compiling. In this recipe, we will discuss these options. We will be working with the project ButtonInput we created earlier in this chapter.

How to do it...

Perform the following steps to compile an iOS project with Xamarin.iOS:

  1. With the project loaded in Xamarin Studio, go to Project | ButtonInput Options.

  2. In the window that appears, select iOS Build from the Build section on the left pad. Select Debug as project configuration and iPhoneSimulator as a platform.

  3. In the Linker behavior field, select Link all assemblies from the combo box.

  4. In the SDK version field, select Default if it is not already selected.

  5. Now go to iOS Application on the left pad.

  6. In the Summary tab, enter Button Input in the Application Name field and 1.0 in the Version field. Select version 6.0 in the Deployment Target combo box. The iOS Application options window is shown in the following screenshot:

  7. Click on the OK button and compile the project by navigating to Build | Build All in the menu bar.

How it works...

We have set up some options for our project. Let's see what these options provide for compilation customization:

iOS build options

The first option we set up relates to the linker. The linker is a tool that was developed by the Xamarin.iOS team and is provided in the SDK. Every time a Xamarin.iOS project is compiled, the compiler does not only compile the project, it also needs all the assemblies of the Xamarin.iOS Framework so that the final app will be able to run on the device (or the simulator). This actually means that every app comes with its own compiled version of the Xamarin.iOS Framework. The final application bundle is quite large in size. This is where the linker comes in. What it does is strips down the assemblies of all the unused code so that the compiler will only compile what is needed and used by the app. This results in much smaller app bundles, a precious asset when it comes to mobile apps. The following are the linker options:

  • Don't Link: Use this option when debugging on the simulator. The linker is turned off and all the assemblies are compiled as they are. It provides faster compilation time.

  • Link SDK assemblies only: The linker only strips down the Xamarin.iOS Framework assemblies. The project assemblies remain intact. It effectively reduces the final size of the app.

  • Link all assemblies: The linker is activated on all assemblies. This reduces the size a bit more. Care needs to be taken when using this option if reflection or serialization is used in the code. Types and methods that are used through reflection in the code are transparent to the linker. If a situation like this exists in the code, decorate these types or methods with the Preserve attribute. This attribute basically informs the linker to be left out of the stripping-down process.

In the SDK version field, we set the iOS SDK version that will be used to compile the app. Setting it to Default automatically selects the highest SDK version installed on the system.


When compiling for the simulator, turning the linker on is not suggested. This is because the compiler is not compiling the Xamarin.iOS assemblies in the iPhoneSimulator platform, hence, they are being used directly. Turning the linker on only causes compilation to take more time to complete. It has no effect in reducing the final app bundle size.

iOS application options

In the iOS Application window of the Build section in the project options, we set up three options:

  • The first option is Application Name. This is the name of the application bundle that will be displayed on the simulator, the device, and on the App Store. As we can see here, we can normally add spaces to the name.

  • The second option, Version, defines the version of the app. It is what will be displayed as the app's version when it is finally distributed through the App Store.

  • The third option, Deployment Target, is the minimum iOS version the app can be installed on.

There's more...

There are two more option windows. These are iOS Bundle Signing and iOS IPA Options. They will be discussed thoroughly in the recipes in Chapter 14, Deploying.

See also

  • The Preparing our app for the App Store recipe in Chapter 14, Deploying


Debugging our application

This recipe provides information on debugging a Xamarin.iOS app on the simulator.

Getting ready

Xamarin.iOS, in combination with Xamarin Studio, provides a debugger for debugging apps either on the simulator or on the device. In this recipe, we'll see how to use the debugger for debugging Xamarin.iOS apps. Open Xamarin Studio and load the ButtonInput project. Make sure to set the project configuration to Debug | iPhone.

How to do it...

Perform the following steps to debug your application:

  1. Xamarin Studio supports breakpoints. To activate a breakpoint on a line, click on the space on the left of the line number to set it. Set a breakpoint on the following line in the ButtonInputViewController.cs file:

    this.labelStatus.Text = "Button tapped!";

    The following screenshot shows what a breakpoint in Xamarin Studio looks like:

  2. Compile and debug the project by clicking on the Run button or by navigating to Run | Start Debugging on the menu bar. Xamarin Studio's status will display the message Waiting for debugger to connect….

  3. When the simulator is opened and the app is loaded, watch the information that is provided in the Application Output pad.

  4. Tap on the app button. Execution will pause and Xamarin Studio will highlight the breakpoint in yellow. Move the mouse over the labelStatus variable in the breakpoint line. A window will be displayed with all the evaluated variable's members, as shown in the following screenshot:

  5. To stop debugging, click on the Stop button in the toolbar.

How it works...

The debugger that is used is called soft debugger. It is called so because it depends on both the runtime and Xamarin Studio, combined to provide one unified debugging platform. When the debugging process starts, Xamarin Studio begins listening for debugging information from the app. The same applies for debugging on both the simulator and the device. When the app executes, it starts sending information back to Xamarin Studio. It then displays that information in the Application Output pad, which is automatically activated. A typical application output when debugging is the information on the assemblies that are loaded, the threads that begin execution, and the breakpoints, if any, that are available.

There's more...

The Console.WriteLine() method can also be used for debugging purposes. The debugger takes care of this and redirects the output of the method to Xamarin Studio's Application Output pad.

App performance when debugging

When compiling for debugging purposes, the compiler produces larger and slower code. This is because it generates extra code that is needed to provide the appropriate debugging information. That's why, when debugging an app, the execution of the app is much slower than on simple running situations. Before producing a release copy of the app, remember to compile it with the Release | iPhone project configuration to avoid slow runtime execution.

Breakpoints in FinishedLaunching

One more reason for not to have complicated code in the FinishedLaunching method is that, in most cases, you will not be able to debug it. If you set a breakpoint in FinishedLaunching, app execution will pause, but iOS will terminate the app when the time limit is reached.

See also

  • The Creating profiles recipe in Chapter 14, Deploying

About the Author

  • Dimitris Tavlikos

    Dimitris Tavlikos is a freelance software developer living in Greece. With over 10 years of professional experience as a programmer, he specializes in mobile development with clients all over the world. Dimitris has a passion for programming, and has recently been awarded the Xamarin MVP designation for his work. He has written a book on iOS development and various articles on his blog.

    Browse publications by this author

Latest Reviews

(2 reviews total)
I find it very difficult to put your books on my ipad, otherwise I would rate them 4 stars.
Package undamaged and books in fine condition, thanks
Book Title
Unlock this book and the full library for only $5/m
Access now