使用 ignoresSafeArea 控制安全区域

了解如何通过使用 ignoresSafeArea 修饰器,在必要时忽略安全区域,创建更加个性化的体验。

使用 ignoresSafeArea 控制安全区域

edgesIgnoringSafeArea vs ignoresSafeArea

.edgesIgnoringSafeArea() 是旧的 API,从 iOS14 开始,推荐使用 .ignoresSafeArea()

ignoresSafeArea(_:edges:) | Apple Developer Documentation
Expands the safe area of a view.

使用 ignoresSafeArea

默认情况下,.ignoresSafeArea() 会忽略所有安全区域边缘(相当于 .edgesIgnoringSafeArea(.all))。

regions 参数

指定忽略的安全区域类型:

  • .all(默认):所有安全区域。
  • .container:忽略由容器(container)定义的安全区域。
  • .keyboard:忽略由键盘定义的安全区域。

.container

通常包括设备的物理边界,例如:

  • 顶部的状态栏或刘海区域(notch)。
  • 底部的 Home 指示器(Home Indicator)或导航栏。
  • 屏幕的圆角区域(在 iPhone 等设备上)。

适用场景:希望视图的内容延伸到屏幕的物理边缘,例如全屏背景、壁纸或装饰性视图

.keyboard

忽略 .keyboard 区域意味着视图会延伸到键盘的上边缘。

适用场景:希望某些视图(例如输入框的背景或装饰性元素)在键盘弹出时仍然占据屏幕底部,而不是被键盘推高。


edges 参数

edges 参数用来更细粒度地控制忽略安全区域的具体边缘(例如顶部、底部、左侧、右侧)。

VStack {
    Text("Hello, World!")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.blue)
        .ignoresSafeArea(edges: .top) // 仅忽略顶部安全区域
}

创建 Apple TV 封面图片效果

在最外层(通常是 ScrollView)使用: 

.ignoresSafeArea(.container, edges: .top)
避免在内层使用,可能无法起效。