Sunday, April 28, 2013

Xamarin Tip: Implementing Protocols and Delegates in iOS Apps


If you are familiar with iOS development using Objective-C and are in the process of converting to using C# in Xamarin, here is a common problem you will frequently encounter. How do you implement protocols and delegates in C#? A classic example is that of the UIAlertView class. Using the UIAlertView class, you can display an alert view together with one or more buttons. When the user taps on the button(s), you want to know which button was tapped.

To implement an Objective-C protocol in C#, simply declare a sub-class of the protocol. In the case of the UIAlertView class, the subclass would look like this:

    public class MyAlertDelegate : UIAlertViewDelegate {
        public override void Clicked (UIAlertView alertview,
        int buttonIndex)
        {
            Console.WriteLine(buttonIndex.ToString() +
            " clicked.");
        }
    }

To implement the protocol, create an instance of the MyAlertDelegate class:

        MyAlertDelegate alertDelegate;
        alertDelegate = new MyAlertDelegate();

And then use it together with the UIAlertView object, like this:

        UIAlertView alert =
            new UIAlertView("Hello, World!",
                            "Welcome to Xamarin, ",
                            alertDelegate,
                            "OK",
                            "Cancel");
        alert.Show();

When a button in the alert view is now tapped, a message will be printed in the console window. 

Attending the Xamarin Training in Singapore. Check out this link for more details. 

No comments: