可以通过使用Xamarin.Forms.PlatformConfiguration.iOSSpecific 命名空间中的Page.SafeAreaInsets 方法检索其Thickness 值来自定义安全区域。然后可以根据需要进行修改并重新分配给页面构造函数中的 Padding 属性或OnAppearing override:
protected override void OnAppearing()
{
base.OnAppearing();
var safeInsets = On<iOS>().SafeAreaInsets();
safeInsets.Bottom = 0;
safeInsets.Top = 35;
safeInsets.Left = 35;
safeInsets.Right = 35;
Padding = safeInsets;
}
人像的效果:
风景的效果:
如果需要在设备方向改变时自定义SafeAreaInsets。有一个OnSizeAllocated的方法可以很方便的使用。
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (width != this.width || height != this.height)
{
this.width = width;
this.height = height;
if (width > height)
{
Console.WriteLine("Landscape");
var safeInsets = On<iOS>().SafeAreaInsets();
safeInsets.Bottom = 0;
safeInsets.Top = 0;
safeInsets.Left = 35;
safeInsets.Right = 35;
Padding = safeInsets;
}
else
{
Console.WriteLine("Portrait");
var safeInsets = On<iOS>().SafeAreaInsets();
safeInsets.Bottom = 0;
safeInsets.Top = 35;
safeInsets.Left = 0;
safeInsets.Right = 0;
Padding = safeInsets;
}
}
}
==================================更新============= ====================
如果需要适配越来越多的设备,可以通过一些手机型号判断(比如iPhone X)来设置两侧安全区域的大小。另外,还可以查看是否包含Navigation Bar或 Tab Bar 修改 Thickness 的大小。应该是
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (width != this.width || height != this.height)
{
this.width = width;
this.height = height;
if (width > height)
{
Console.WriteLine("Landscape");
var safeInsets = On<iOS>().SafeAreaInsets();
// whether is iPhone X
if (deveiceType.Equals("iPhone X"))
{
//whether contain Navigation Bar
if (ContainNavigationBar) { safeInsets.Top = 44; } else { safeInsets.Top = 0; }
//whether conatin Tab Bar
if (ContainTabBar) { safeInsets.Bottom = 34; } else { safeInsets.Bottom = 0; }
}
safeInsets.Left = 35;
safeInsets.Right = 35;
Padding = safeInsets;
Padding = safeInsets;
}
else
{
Console.WriteLine("Portrait");
var safeInsets = On<iOS>().SafeAreaInsets();
// whether is iPhone X
if (deveiceType.Equals("iPhone X"))
{
//whether contain Navigation Bar
if (ContainNavigationBar) { safeInsets.Top = 84; } else { safeInsets.Top = 44; }
//whether conatin Tab Bar
if (ContainTabBar) { safeInsets.Bottom = 34; }else{ safeInsets.Bottom = 0; }
}
safeInsets.Left = 0;
safeInsets.Right = 0;
Padding = safeInsets;
}
}
}
只要苹果以后不改变状态栏的高度,我认为硬编码设置的高度不会有问题。