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 效果更好

相关推荐
MaAidan3 小时前
用 Agent 排查线上问题:SLS 日志分析 + DB/Redis 数据验证,一条链路搞清楚
前端·bootstrap·html
howard20052 天前
英中 / 中英对照制作程序:操作指南
spring boot·bootstrap·thymeleaf·操作指南·对照制作程序
重生之我是Java开发战士2 天前
【Redis】Java & JavaSpring 客户端
java·redis·bootstrap
汤米粥5 天前
目前流行的前端 CSS 框架
前端·css·bootstrap·ant design·‌tailwind css·bulma
Wang's Blog6 天前
Java 项目实战: 交友项目 - 圈子互动章总结与自检清单
java·bootstrap·交友
海鸥-w6 天前
Redis 配置与排错说明
java·数据库·redis·bootstrap
乐茵lin9 天前
Redis 持久化机制详解:RDB 与 AOF
redis·bootstrap·mybatis
小胡202411 天前
DzzOffice V2.4.2 版本上线!安全加固 × 网盘体验全面升级
服务器·bootstrap·php·协同办公·dzzoffice
OxYGC11 天前
[工程] Redis 配置文件redis.conf全解析
数据库·redis·bootstrap