Cross Platform
Android
iOS
Mac
Test Cloud

Walkthrough - Using Custom Controls with the Xamarin Designer for iOS

Building Controls for use in the Xamarin Designer for iOS

This article provides a step-by-step walkthrough showing how to create a custom control and use it in the Xamarin Designer for iOS. It shows how to make a control available in the designer’s Toolbox so it can be drag/dropped onto a view. Additionally, it shows how to implement a control so it renders properly at design time and runtime, as well as how to create properties that can be set at design time.

Requirements

The Xamarin Designer for iOS is available in Xamarin Studio 5.0 for Mac and Xamarin 3.0 for Windows

This guide assumes a familarity with the contents convered in the Getting Started guides.

Walkthrough

Starting in Xamarin.Studio 5.5, the way in which custom controls are created is slightly different to earlier versions. To create a custom control, either the IComponent interface is required (with the associated implementation methods) or the class can be be annotated with [DesignTimeVisible(true)]. The latter method is being used in the following walkthrough example.

  1. Create a new solution named ScratchTicket from the iOS > Classic API > iPhone > Single View Application template:
  2. Create a new empty class file named ScratchTicketView:
  3. Add the following code for ScratchTicketView class:
  4. using System;
    using System.ComponentModel;
    using System.Drawing;
    using MonoTouch.CoreGraphics;
    using MonoTouch.Foundation;
    using MonoTouch.UIKit;
    
    namespace ScratchTicket
    {
        [Register("ScratchTicketView"), DesignTimeVisible(true)]
        public class ScratchTicketView : UIView
        {
            CGPath path;
            PointF initialPoint;
            PointF latestPoint;
            bool startNewPath = false;
            UIImage image;
    
            public ScratchTicketView (IntPtr p) : base(p)
            {
                Initialize ();
            }
    
            public ScratchTicketView ()
            {
                Initialize ();
            }
    
            void Initialize ()
            {
                initialPoint = PointF.Empty;
                latestPoint = PointF.Empty;
                BackgroundColor = UIColor.Clear;
                Opaque = false;
                path = new CGPath ();
                image = UIImage.FromBundle ("FillTexture.png");
                SetNeedsDisplay ();
            }
    
            public override void TouchesBegan (NSSet touches, UIEvent evt)
            {
                base.TouchesBegan (touches, evt);
    
                UITouch touch = touches.AnyObject as UITouch;
    
                if (touch != null) {
                    initialPoint = touch.LocationInView (this);
                }
            }
    
            public override void TouchesMoved (NSSet touches, UIEvent evt)
            {
                base.TouchesMoved (touches, evt);
    
                var touch = touches.AnyObject as UITouch;
    
                if (touch != null) {
                    latestPoint = touch.LocationInView (this);
                    SetNeedsDisplay ();
                }
            }
    
            public override void TouchesEnded (NSSet touches, UIEvent evt)
            {
                base.TouchesEnded (touches, evt);
                startNewPath = true;
            }
    
            public override void Draw(RectangleF rect)
            {
                 base.Draw(rect);
    
                 using (var g = UIGraphics.GetCurrentContext())
                 {
                     g.SetFillColor ((UIColor.FromPatternImage (image).CGColor));
                     g.FillRect(rect);
    
                     if (!initialPoint.IsEmpty)
                     {
                        g.SetLineWidth(20);
                        g.SetBlendMode(CGBlendMode.Clear);
                        UIColor.Clear.SetColor();
    
                        if (path.IsEmpty || startNewPath)
                        {
                            path.AddLines(new PointF[] { initialPoint, latestPoint });
                            startNewPath = false;
                        }
                        else
                        {
                            path.AddLineToPoint(latestPoint);
                        }
    
                        g.SetLineCap(CGLineCap.Round);
                        g.AddPath(path);        
                        g.DrawPath(CGPathDrawingMode.Stroke);
                    }
               }
           }
        }
    }
  5. Add the FillTexture.png, FillTexture2.png and Monkey.png files (available with the sample code that accompanies this article) to the Resources folder.
  6. Double-click the MainStoryboard.storyboard file to open it in the designer.
  7. Drag/drop an Image View from the Toolbox onto the view in the storyboard.
  8. Select the Image View and change its Image property to Monkey.png.
  9. Build the project so that the Scratch Ticket View will appear under Custom Components in the Toolbox.
  10. Drag/drop a Scratch Ticket View so that it appears over the monkey image, as shown below:
  11. Under the Layout tab, set Autosizing for both the Image View and Scratch Ticket View as shown below so that they do not stretch and remain centered.
  12. Add a Default-568h@2x.png image in the Info.plist so that the application will appear full screen on a Retina 4-inch display (also set other images as desire).
  13. Run the application and "scratch off” the image to reveal the monkey.

Adding Design-Time Properties

The designer also includes design-time support for custom controls of property type numeric, enumeration, string, bool, SizeF, UIColor, and UIImage. To demonstrate, let’s add a property to the ScratchTicketView to set the image that is "scratched off.”

Add the following code to the ScratchTicketView class for the property:

[Export("Image"), Browsable(true)]
public UIImage Image 
{
    get { return image; }
    set { 
            image = value;
            SetNeedsDisplay ();
        }
}

We may also want to add a null check to the Draw method, like so:

public override void Draw(RectangleF rect)
{
    base.Draw(rect);

    using (var g = UIGraphics.GetCurrentContext())
    {
        if (image != null)
            g.SetFillColor ((UIColor.FromPatternImage (image).CGColor));
        else
            g.SetFillColor (UIColor.LightGray.CGColor);

        g.FillRect(rect);

        if (!initialPoint.IsEmpty)
        {
             g.SetLineWidth(20);
             g.SetBlendMode(CGBlendMode.Clear);
             UIColor.Clear.SetColor();

             if (path.IsEmpty || startNewPath)
             {
                 path.AddLines(new PointF[] { initialPoint, latestPoint });
                 startNewPath = false;
             }
             else
             {
                 path.AddLineToPoint(latestPoint);
             }

             g.SetLineCap(CGLineCap.Round);
             g.AddPath(path);       
             g.DrawPath(CGPathDrawingMode.Stroke);
        }
    }
}

Including an ExportAttribute and a BrowsableAttribute with the argument set to true results in the property being displayed in the designer’s Property panel. Changing the property to another image included with the project, such as FillTexture2.png, results in the control updating at design time, as shown below:

Summary

In this article we walked through how to create a custom control, as well as consume it in an iOS application using the iOS designer. We saw how to create and build the control to make it available to an application in the designer’s Toolbox. Additionally, we looked at how to implement the control such that it renders properly at both design time and runtime, as well as how to expose custom control properties in the designer.