如何获取各型号带刘海/灵动岛iPhone的真实刘海/灵动岛尺寸?
解决方案说明
苹果官方没有公开各型号iPhone刘海/灵动岛的精确尺寸文档,因为苹果推荐开发者依赖系统提供的布局API进行适配,而非硬编码设备尺寸,避免因机型迭代导致布局失效。
针对你遇到的横屏布局不对称问题,推荐以下两种更可靠的适配方式:
1. 利用SwiftUI原生布局自动适配
直接让视图遵循系统安全区域,无需手动计算宽度:
struct ContentView: View { var body: some View { Rectangle() .fill(Color.red) .edgesIgnoringSafeArea(.vertical) // 竖屏方向忽略安全区,横屏时自动避开刘海/灵动岛 .frame(maxWidth: .infinity) } }
如果需要更精细的控制,可以结合safeAreaInset调整内容与安全区的间距:
struct ContentView: View { var body: some View { Rectangle() .fill(Color.red) .safeAreaInset(edge: .trailing) { Color.clear.frame(width: 0) // 根据实际需求调整,或直接依赖系统默认安全区 } .frame(maxWidth: .infinity) } }
2. 通过UIKit API获取精确可视区域
如果你确实需要获取去掉刘海/灵动岛后的精确可用区域,可以通过UIWindowScene的visibleFrame属性,这个属性返回的是屏幕去掉所有系统遮挡(包括刘海、灵动岛、圆角)后的实际可显示区域:
import SwiftUI struct ContentView: View { @State private var visibleWidth: CGFloat = 0 var body: some View { Rectangle() .fill(Color.red) .frame(width: visibleWidth) .onAppear { guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = scene.windows.first else { return } visibleWidth = window.screen.visibleFrame.width } .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = scene.windows.first else { return } visibleWidth = window.screen.visibleFrame.width } } }
visibleFrame会自动适配横屏/竖屏方向,以及不同机型的刘海/灵动岛尺寸,无需手动处理机型差异。
注意事项
- 避免硬编码任何设备相关的尺寸值,苹果会持续更新机型,硬编码会导致新机型布局异常。
- 优先使用SwiftUI的原生布局机制,系统会自动处理安全区、方向切换等适配逻辑。
内容的提问来源于stack exchange,提问作者MassMover
相关产品推荐
相关产品推荐

