为什么 SwiftUI View 背景会延伸到安全区域?

Why does SwiftUI View background extend into safe area?

这是导航到第二个视图的视图:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink {
                SecondView()
            } label: {
                Text("Go to 2nd view")
            }
        }
        
    }
}


 struct SecondView: View {
     var body: some View {
         ZStack {
             Color.red
             VStack {
                 Text("This is a test")
                     .background(.green)
                 //Spacer() // <--If you add this, it pushes the Text to the top, but its background no longer respects the safe area--why is this?
             }
         }
     }
 }

在第二个屏幕上,Text 视图的绿色背景只延伸到它的边框,这是有道理的,因为文本是一个拉入视图:

现在,如果在 Text() 之后添加 Spacer()Text 视图将推到 VStack 的顶部,这是有道理的,但为什么它绿色背景突然推入安全区?

Apple 文档 here 中说:

By default, SwiftUI sizes and positions views to avoid system defined safe areas to ensure that system content or the edges of the device won’t obstruct your views. If your design calls for the background to extend to the screen edges, use the ignoresSafeArea(_:edges:) modifier to override the default.

但是,在这种情况下,我没有使用 ignoresSafeArea,那么为什么它的行为就像我使用的一样,而不是像 Apple 所说的那样执行默认值,即避开安全区域?

您认为您使用 old background modifier version。 但实际上,上面的代码使用了一个新代码,introduced in iOS 15 version of background modifier 默认情况下忽略所有安全区域边缘:

func background<S>(_ style: S, ignoresSafeAreaEdges edges: Edge.Set = .all) -> some View where S : ShapeStyle

要解决此问题,如果您的应用程序部署目标 < iOS 15.0,只需将 .background(.green) 替换为 .background(Color.green),否则使用 a new modifier.background { Color.green }