Xamarin forms - Set SetUseSafeArea to true globally for all pages

Viewed 894

In xamarin forms you can use

On<iOS>().SetUseSafeArea(true);

And this will ensure your views don't display over any notches/unsafe areas.

I'm wondering if there's any way I can set this globally so I don't have to keep adding that line of code in each content page.

A solution without a custom renderer is preferred (unless this is the only way it can be achieved)

3 Answers

The only way is that enable safe area in custom renderer of Page .

[assembly: ExportRenderer(typeof(Xamarin.Forms.Page), typeof(MyRenderer))]
namespace App1.iOS
{
    class MyRenderer :PageRenderer
    {

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            var page = Element as Xamarin.Forms.Page;

            page.On<Xamarin.Forms.PlatformConfiguration.iOS>().SetUseSafeArea(true);
        }

    }
}

Add this to your Application.Resources

<Application 
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:iOsSpecific="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
x:Class="YourApp.App">
<Application.Resources>
    <ResourceDictionary>
        
        <Style TargetType="iOsSpecific:Page">
            <Setter Property="UseSafeArea" Value="True"/>
        </Style>

It will target all Page on iOS platform specific globally.

This works for me, in my App.xaml:

<Style TargetType="ContentPage" ApplyToDerivedTypes="True">
    <Setter Property="BackgroundColor" Value="White" />
    <Setter Property="iOsSpecific:Page.UseSafeArea" Value="True"/>
</Style>

With the import up top:

xmlns:iOsSpecific="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
Related