HTML中获取iOS手机安全区域SafeArea

发布时间 2023-12-28 20:18:33作者: 不停奔跑的蜗牛

苹果手机iPhone X及以上版本都带有刘海屏,14pro以上版本变成了所谓灵动岛,所以顶部和底部都有一个安全区域。

手机型号尺寸(pt)倍数屏幕(px)状态栏高度顶部安全距离底部安全距离
iPhone14Pro、iPhone15Pro、iPhone15 393 * 852 3 1179 * 2556 54pt 59pt 34pt(竖屏) / 21pt(横屏)
iPhone14ProMax iPhone15ProMax、iPhone15plus 430 * 932 3 1290 * 2796 54pt 59pt 34pt(竖屏) / 21pt(横屏)
iPhone12、iPhone12Pro、iPhone13、iPhone13Pro、iPhone14 390 * 844 3 1170 * 2532 47pt 47pt 34pt(竖屏) / 21pt(横屏)
iPhone12ProMax、iPhone13ProMax、iPhone14Plus 428 * 926 3 1284 * 2778 47pt 47pt 34pt(竖屏) / 21pt(横屏)
iPhone12mini、iPhone13mini 375 * 812 3 1125 * 2436 50pt 50pt 34pt(竖屏) / 21pt(横屏)
iPhoneXS Max、iPhone11ProMax 414 * 896 3 1242 * 2688 44pt 44pt 34pt(竖屏) / 21pt(横屏)
iPhoneX、iPhoneXS、iPhone 11 Pro 375 * 812 3 1125 * 2436 44pt 44pt 34pt(竖屏) / 21pt(横屏)
iPhoneXR、iPhone 11 414 * 896 2 828* 1792 48pt 48pt 34pt(竖屏) / 21pt(横屏)
iPhone6 Plus、iPhone6s Plus、iPhone7 Plus、iPhone8 Plus 414 * 736 3 1242x2208 20pt 20pt ---
iPhone6、iPhone6s、iPhone7、iPhone8、iPhoneSE2、iPhoneSE3 375 * 667 2 750 * 1334 20pt 20pt ---

在web网页中需要根据安全区域从而适当的调整布局,  那么如何获取顶部和底部安全区域的高度呢。直接上代码

const bottomAreaHeight = ref(0)
let safeAreaHeightValue = 0
let topSafeAreaHeight = 0
let bottomSafeAreaHeight = 0
onMounted(() => {
  // 获取底部安全区域的高度
  const isIphone = /iPhone/i.test(navigator.userAgent)

  if (isIphone) {
    safeAreaHeightValue = window.screen.height - window.innerHeight

    if (safeAreaHeightValue >= 44) {
      bottomSafeAreaHeight = 34
    }

    switch (safeAreaHeightValue) {
      case 93:
      case 59:
        topSafeAreaHeight = 59
        break

      case 81:
      case 47:
        topSafeAreaHeight = 47
        break

      case 84:
      case 50:
        topSafeAreaHeight = 50
        break

      case 78:
      case 44:
        topSafeAreaHeight = 44
        break

      case 82:
      case 48:
        topSafeAreaHeight = 48
        break

      case 20:
        topSafeAreaHeight = 20
        break

      default:
        break
    }
  }
  bottomAreaHeight.value = bottomSafeAreaHeight

 为什么是两种数值对应一个相同的值呢,主要原因是iOS端有可能设置Webview的忽略安全距离

import SwiftUI
import WebKit
struct ContentView: View {
    @State var url: String? = "https://www.baidu.com"
    var body: some View {
        SWKWebView(url: $url).edgesIgnoringSafeArea(.all)
        //top 93 bottom 59 all 59
    }
}

#Preview {
    ContentView()
}

拿iPhone15举例来说,edgesIgnoringSafeArea(.all)和edgesIgnoringSafeArea(.bottom),window.screen.height:852,innerHeight:793,差值为59,

 

edgesIgnoringSafeArea(.top)或者不设置时 "innerHeight":759,"screnHeight":852,差值为93。

另外需要注意设置edgesIgnoringSafeArea(.top)和all时顶部如果有返回按钮啥的注意距离顶部的距离,否则有可能造成跑到状态来上去了