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" />

相关推荐
编程乐学(Arfan开发工程师)10 天前
75、单元测试-嵌套测试
前端·javascript·redis·python·单元测试·bootstrap
编程乐学(Arfan开发工程师)10 天前
74、单元测试-前置条件
redis·python·阿里云·单元测试·云计算·bootstrap
Beginner x_u11 天前
[AJAX 实战] 图书管理系统下 编辑图书
前端·javascript·ajax·bootstrap
Beginner x_u11 天前
【AJAX 实战】图书管理系统上 渲染图书列表+新增图书+删除图书
前端·ajax·bootstrap
vx Biye_Design13 天前
SSM学生社团管理系统-计算机毕业设计源码75136
spring boot·sql·mysql·ajax·bootstrap·mybatis
得物技术14 天前
Redis 是单线程模型?|得物技术
bootstrap·html
悟能不能悟15 天前
Redis的GEO详解
前端·redis·bootstrap
axinawang21 天前
通过RedisCacheManager自定义缓存序列化(适用通过注解缓存数据)
前端·spring·bootstrap
天天打码22 天前
Bootstrap Table开源的企业级数据表格集成
前端·开源·bootstrap
ayuday25 天前
Bootstrap Table强大的web数据表格渲染框架
bootstrap·bootstrap table