Recently, I’ve started to work on a new Xamarin.iOS project and I wanted to be able to to visualize the layers / margin of the views displayed on screen.

Let’s take an simple example to explain you what I mean:

var uiView = new UIView(new CGRect(0, 40, 150, 25));

var uiLabel = new UILabel(new CGRect(50, 25, this.View.Bounds.Width, 40)) { Text = "Demo Text" };


As you can see, this is a very basic code used to add a label in a view:

According to the screenshot, nothing is wrong but how can we be sure that the sizes / margins are correct ? That the label is correctly positioned inside the label?

I’ve been doing a lot of Xamarin development during the last years but I was quite surprised to see that nothing was available (as far as I know) to display the layers / margins. Of course, Xamarin Inspector can be used to display the layers of all your application but that’s not exactly what I was looking for.

So I decide to implement my own solution, which is quite simple actually:

public static class UIViewExtensions
    public static void EnableDebugLayers(this UIView rootView)
        rootView.Layer.Bounds = new CGRect(rootView.Bounds.X, rootView.Bounds.Y, rootView.Bounds.Width, rootView.Bounds.Height);
        rootView.Layer.BorderColor = UIColor.Red.CGColor;
        rootView.Layer.BorderWidth = 3;
        rootView.Layer.CornerRadius = 0;

        foreach (var subView in rootView.Subviews)

By activating this extension, we are now able to visualize our layers / margins:

Now, we are able to see that despite the fact we put the label inside the view, it doesn’t render well / correctly!

Of course, in a real application, we’ll use constraints, etc. but I find myself the need to often build user interfaces just by code so this helper will help me and, I hope, you too 🙂

You can find the code there:

Happy coding!

Improve Azure Function logging with function filters Auditing your Azure DevOps Services instance

Leave a Reply

Your email address will not be published. Required fields are marked *