Josh Earl Josh Earl - 10 months ago 89
C# Question

UILabel with padding in Xamarin.iOS?

I'm trying to create a

with padding in my Xamarin.iOS app. The most popular solution in native Objective-C apps is overriding

- (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);


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

Any suggestions?

Answer Source

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));