How to create a category in xamarin ios?

I want to add some methods to UITextfield class along with IBInspectable and IBDesignable properties. I can do it in objective-C but am not finding a way to do the same thing in Xamarin/C#. Can anyone help me to do this?

Thanks for your time in advance.

1 answer

  • answered 2017-06-17 18:59 apineda

    In Xamarin (really this is on C#) what you know as Category in Objective-C is known as Extension Methods.

    Extension methods allows you to add functionality to a class without subclassing it, as you might already imagined.

    So for example if you want to add a method to the UILabel class to check for null and Empty into the text property you could do something like this:

    public static class UILabelExtensionMethod
        public static bool TextIsNullOrEmpty (this UILabel label)
            return string.IsNullOrEmpty (label?.Text);

    Now with the above you can call that method on any UILabel object

    var myLabel = new UILabel ();
    var isEmpty = myLabel.TextIsNullOrEmpty ();

    However, Extension methods cannot be used with the IBInspectable and IBDesignable annotations. These annotations are only available when sub-classing and as @Demitrian indicated this is called Custom Controls.

    Hope this helps.-