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

相关推荐
island13142 天前
【Redis#10】渐进式遍历 | 数据库管理 | redis_cli | RES
数据库·redis·bootstrap
IAtlantiscsdn2 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap
李游Leo3 天前
Redis 持久化与高可用实践(RDB / AOF / Sentinel / Cluster 全解析)
java·spring·bootstrap
二掌柜,酒来!5 天前
完美解决:应用版本更新,增加字段导致 Redis 旧数据反序列化报错
redis·spring·bootstrap
tangweiguo030519876 天前
基于 Django 与 Bootstrap 构建的现代化设备管理平台
后端·django·bootstrap
不爱洗脚的小滕7 天前
【Redis】Scan 命令使用教程:高效遍历海量数据
数据库·redis·bootstrap
睡觉的时候不会困7 天前
Redis 主从复制详解:原理、配置与主从切换实战
数据库·redis·bootstrap
猫头虎-前端技术7 天前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
梦中的天之酒壶8 天前
Redis Stack扩展功能
数据库·redis·bootstrap
2501_920047039 天前
Redis-集群
数据库·redis·bootstrap