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

相关推荐
晨陌y2 天前
redis_exporter + Prometheus监控Redis: 指标采集、告警与远程抓取
redis·bootstrap·prometheus
dllmayday3 天前
Bootstrap三开关样式
前端·javascript·bootstrap
随风M记忆s5 天前
Redis支持事务吗?了解Redis的持久化机制吗?
数据库·redis·bootstrap
IT_Octopus7 天前
Redis 数据存储与序列化完全指南:从 byte[] 到 Object:Redis 序列化机制与生产环境选型
数据库·redis·bootstrap
千河殇 多想和她9 天前
线上 Redis 突然“爆”了,怎么办?
数据库·redis·bootstrap
海兰11 天前
【高速缓存】RedisVL 索引迁移指南:安全演进索引结构
前端·数据库·redis·安全·缓存·bootstrap
shmily麻瓜小菜鸡12 天前
前端“伪防盗链”方案
前端·javascript·vue.js·bootstrap·echarts
她说可以呀12 天前
Redis哨兵
数据库·redis·bootstrap
Season45015 天前
Redis命令 (generic即通用命令)
数据库·redis·bootstrap
耀耀_很无聊16 天前
13_Spring Boot 3.5.8 + Redisson 3.45.1 导致 Sa-Token 登录 StackOverflowError
spring boot·后端·bootstrap