Search code examples
c#iosiphonexamarin.iosuilabel

UILabel with padding in Xamarin.iOS?


I'm trying to create a UILabel with padding in my Xamarin.iOS app. The most popular solution in native Objective-C apps is overriding drawTextInRect:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

As simple as this seems, I can't quite figure out how to translate it to C#. Here's my best stab at it:

internal class PaddedLabel : UILabel
{
    public UIEdgeInsets Insets { get; set; }

    public override void DrawText(RectangleF rect)
    {
        var padded = new RectangleF(rect.X + Insets.Left, rect.Y, rext.Width + Insets.Left + Insets.Right, rect.Height);

        base.DrawText(padded);
    }
}

This does seem to move the label's text, but it doesn't resize the label.

I think the main issue is that I can't find the Xamarin equivalent of UIEdgeInsetsInsetRect.

Any suggestions?


Solution

  • The C# equivalent of the ObjC function UIEdgeInsetsInsetRect is a instance method of UIEdgeInsets named InsetRect and it's not identical to your RectangleF calculations (which is likely your problem).

    To use it you can do:

    public override void DrawText(RectangleF rect)
    {
        base.DrawText (Insets.InsetRect (rect));
    }