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

相关推荐
前端橙一陈2 天前
彻底理解 Bootstrap 的响应式断点机制:从 CSS 到 SCSS 的实现原理
css·bootstrap·scss
速易达网络5 天前
Bootstrap 5 响应式网站首页模板
前端·bootstrap·html
祈祷苍天赐我java之术5 天前
Redis 数据类型与使用场景
java·开发语言·前端·redis·分布式·spring·bootstrap
哥哥还在IT中6 天前
Redis多线程架构深度解析-从单线程到I/O Threading
redis·架构·bootstrap
ajsbxi11 天前
【Redis】缓存读/写操作流程
redis·笔记·spring·缓存·bootstrap
非凡的世界11 天前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp
爬山算法12 天前
Redis(60) Redis的复制延迟如何优化?
redis·bootstrap·php
凯子坚持 c15 天前
Redis Hash 全解析:从入门到精通,解锁高性能对象存储的钥匙
redis·bootstrap·哈希算法
kjl53656620 天前
Redis配置文件(redis.conf)
redis·bootstrap·php
祈祷苍天赐我java之术20 天前
Redis 有序集合解析
java·前端·windows·redis·缓存·bootstrap·html