Maui blazor ios 按设备类型设置是否启用safeArea

需求,新做了个app, 使用的是maui blazor技术,里面用了渐变背景,在默认启用SafeArea情况下,底部背景很突兀

  1. 由于现版本maui在SafeArea有点bug,官方教程的<ContentPage SafeArea=false不生效,于是要用以下代码hack一下

    复制代码
             Microsoft.Maui.Handlers.LayoutHandler.Mapper.AppendToMapping("Custom", (h, v) =>
             {
                 if (v is Layout layout)
                 {
                     layout.IgnoreSafeArea = true;
                 }
             });

带来的问题是,网页上下穿透了。

  1. 继续深入研究,用以下代码设置刘海屏上边距

    复制代码
     protected override void OnAppearing()
     {
         base.OnAppearing();
         if (withSafeArea)
         {
             var safeInsets = On<iOS>().SafeAreaInsets();
                 On<iOS>().SetUseSafeArea(false);
                 safeInsets.Top = 35;
                 Padding = safeInsets;
         } 
     }

存在的问题是,非刘海屏设备也设置了上边距

  1. 最终代码,检查设备类型,按需配置上边距

    using Microsoft.Maui.Controls.PlatformConfiguration;
    using Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;

    namespace MyApp.Maui;

    public partial class MainPage : ContentPage
    {
    bool withSafeArea = false;
    public MainPage()
    {
    InitializeComponent();

    复制代码
         if (DeviceInfo.Current.Idiom == DeviceIdiom.Phone)
         {
             var screenSize = DeviceDisplay.MainDisplayInfo;
             if (screenSize.Height / screenSize.Density >= 812.0f)
             {
                 withSafeArea = true;
             }
         }
    
         if (withSafeArea) { 
             Microsoft.Maui.Handlers.LayoutHandler.Mapper.AppendToMapping("Custom", (h, v) =>
             {
                 if (v is Layout layout)
                 {
                     layout.IgnoreSafeArea = true;
                 }
             });
         }
     }
    
     protected override void OnAppearing()
     {
         base.OnAppearing();
         if (withSafeArea)
         {
             var safeInsets = On<iOS>().SafeAreaInsets();
                 On<iOS>().SetUseSafeArea(false);
                 safeInsets.Top = 35;
                 Padding = safeInsets;
         } 
     }

    }

  2. 题外话,网页可加上 viewport-fit=cover 效果更好

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />

相关推荐
小股虫19 小时前
Redis数据结构底层深度解析:写入与读取的高效逻辑
数据结构·redis·bootstrap
阿猿收手吧!20 小时前
【Linux】Ubuntu配置开发环境合集
linux·ubuntu·bootstrap
山土成旧客1 天前
机器学习打卡DAY18 | 回归问题全解析:模型对比、置信区间与Bootstrap实战
机器学习·回归·bootstrap
爬山算法2 天前
Redis(169)如何使用Redis实现数据同步?
前端·redis·bootstrap
U盘失踪了3 天前
Django Bootstrap 下载到本地使用,避免 CDN 超时
python·django·bootstrap
爬山算法3 天前
Redis(166)如何使用Redis实现实时统计?
java·redis·bootstrap
liliangcsdn4 天前
如何用bootstrap模拟估计pass@k
大数据·人工智能·bootstrap
u***32435 天前
redis连接服务
数据库·redis·bootstrap
原来是桀倾呐6 天前
Quasar Framework 与 大清朝的 Bootstrap技术 差异
bootstrap
野生技术架构师6 天前
SpringBoot项目使用Redis对用户IP进行接口限流
spring boot·redis·bootstrap