Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
Josh Earl Avatar asked Jan 16 '14 14:01

Josh Earl


1 Answers

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));
}
like image 109
poupou Avatar answered Oct 09 '22 08:10

poupou