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

相关推荐
Mr.45672 天前
Spring Boot集成Redis:单机、哨兵、集群三种模式统一配置实战
spring boot·redis·bootstrap
q5431470872 天前
Redis Desktop Manager(Redis可视化工具)安装及使用详细教程
redis·git·bootstrap
uimaker2 天前
uimaker响应式jQuery Easyui+Bootstrap多配色主题设计
前端框架·bootstrap·html·jquery·easyui·后台模版
油丶酸萝卜别吃2 天前
springboot项目中redis常见的增删改查操作是哪些?
spring boot·redis·bootstrap
一个有温度的技术博主3 天前
Redis系列八:Jedis连接池在java中的使用
java·redis·bootstrap
anzhxu3 天前
Ubuntu上安装、使用Redis的详细教程
redis·ubuntu·bootstrap
難釋懷3 天前
Lua语法入门
junit·bootstrap·lua
柒.梧.4 天前
Redis通用命令+五大核心数据结构
前端·bootstrap·html
6+h4 天前
【Redis】底层原理解析(SDS / 跳表 / IO多路复用 / 单线程模型)
数据库·redis·bootstrap
云姜.6 天前
Redis 缓存穿透/缓存雪崩/缓存击穿问题
redis·缓存·bootstrap