Thursday, February 07, 2013

Creating a Custom UIView in MonoTouch and using it in the XCode XIB editor

This was my answer in response to:

  I cannot figure out how to add a custom control to the XIB.

in http://stackoverflow.com/questions/14738964/how-do-you-add-a-custom-uiviewcontroller-to-existing-xib/

----


For a normal UIView, the basic steps you need to go through are:
  1. Create your custom view in C# as a class

    public class MyView
    {
    }
    
    
  2. Add the UIView base class to it, add a Register attribute and add two constructors:

    [Register("MyView")]
    public class MyView : UIView
    {
        public MyView() {}
        public MyView(IntPtr handle) : base(handle) {}
    }
    
    
  3. To make it do something useful, then add a Draw implementation:

    public override Draw(RectangleF rect)
    {
        var context = UIGraphics.CurrentGraphics();
        UIColor.Red.SetFill();
        context.FillEclipseInRect(rect);
    }
    
    
  4. Save and Build your project
  5. Now double click on the XIB for the UIViewController in which you want to use your custom view.
  6. This will open up the XIB editor in xCode
     
  7. In the editor, add a UIView to the design surface
  8. Select that UIView and in the Identity Inspector, set the UIView's "Custom Class" to "MyView"
  9. Save everything in XCode
  10. Return to MonoDevelop, build and run
There's a video of this flow available at: - http://www.youtube.com/watch?v=ggwO46dd-50&feature=youtube_gdata




For a custom UICollectionView, UILabel, UITableViewCell, or any other UIView base class, then you follow similar steps, just with a different base class and with different constructors too in order to support the specific View.

For a video about custom Table cells, see: http://slodge.blogspot.co.uk/2013/01/uitableviewcell-using-xib-editor.html

4 comments:

  1. Hi Stuart, great tip!

    But what do I do if I create the custom view in Interface Builder (and not in code)? So I create a custom view in IB, and then specify it to be of type CustomView. I then add various UI controls to it.

    In CustomViewController's view, I add a UIView and change its type to my CustomView. But when I compile and run, that view is blank!

    ReplyDelete
    Replies
    1. Can you post a repo? Will get it working ;)

      Delete
  2. Hi Stuart

    Thanks for the quick response! Apologies for my delayed one; basic repo at https://github.com/mrtnkrstn/MyCustomView

    Thank you so much for helping with this! Noticed that you are at Xamarin Evolve, wish I was able to attend. Following the proceedings in spirit; enjoy!

    ReplyDelete
  3. Hi Stuart

    Thanks for your help :) I somehow never stumbled upon Nib.Instantiate(). Would have been so nice if all of this could have been done straight in Interface Builder though.

    Again, thanks for the help!

    ReplyDelete