.NET MAUI Label controls do not have the capability to adjust their font size to accommodate the width of the content. In Xamarin.Forms, you had to use a view renderer in the platform-specific project to accomplish this. Thankfully, it’s much easier in .NET MAUI.

This blog post shows how to customize a label control for use in .NET MAUI for the iOS platform using a handler mapper.

Start by building an app by following these instructions.

Replace the <ScrollView> and its contents in MainPage.xaml with the following:

<VerticalStackLayout BackgroundColor="Yellow"
                     Padding = "10"
                     Spacing="10">
    <Label
                     BackgroundColor="Aqua"
                     FontSize = "32"
                     Text="Lorem"/>
    <Label
                     BackgroundColor="Fuchsia"
                     FontSize = "32"
                     Text="Lorem ipsum dolor sit amet."/>
    <Label
                     BackgroundColor="Lime"
                     FontSize = "32"
                     Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit."/>
    <Label
                     BackgroundColor="Silver"
                     FontSize = "32"
                     Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero."/>
</VerticalStackLayout>

Build your new app and run it with the iPhone SE (3rd generation) simulator. Notice that the 2nd - 4th labels have added more lines to accommodate the text. This is what it should look like:

If it doesn’t then either you or I missed a step here.

Change the Label in MainPage.xaml to local:LabelAdjustsFontSizeToFitWidth and add the following line to the ContentPage element while replacing your own namespace for HelloWorldMaui.

Add a C# class to the project with the following content.

namespace HelloWorldMaui
{
    public class LabelAdjustsFontSizeToFitWidth : Label 
    {
        static LabelAdjustsFontSizeToFitWidth()
        {
            Microsoft.Maui.Handlers.LabelHandler.Mapper.AppendToMapping("AdjustsFontSizeToFitWidth", (handler, view) => 
            {
#if IOS    
                handler.PlatformView.AdjustsFontSizeToFitWidth = true;
                handler.PlatformView.Lines = 1;
                handler.PlatformView.BaselineAdjustment = UIKit.UIBaselineAdjustment.AlignCenters;
                handler.PlatformView.LineBreakMode = UIKit.UILineBreakMode.Clip;
#endif    
            });
        }
    }
}

Ditto replacing your own namespace for HelloWorldMaui. Build and run on the same simulator. You should get results that look like this. Notice that the font size in the 2nd - 4th labels are adjusted so the content fits the width of the label in one line.

Making the height adjust its size is an exercise for the reader. If you solve it, please share.

Also, if you figure out how to do this with Android, please share. I haven’t figured out how to do that yet.

Updated: