swiftUI:可以让背景颜色忽略安全区域并且内容遵循安全区域吗?

mit*_*oos 1 swiftui

我想戴上.edgesIgnoringSafeArea(.all)一个,VStack以便背景颜色覆盖整个视图。

VStack {
    Text("Foo")
}
.edgesIgnoringSafeArea(.all)
.background(Color.red)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这覆盖了背景颜色的整个视图,这是我想要的行为,但文本现在也忽略了安全区域。有没有更好的方法让背景覆盖整个视图而不牺牲内部内容的安全区域覆盖?

ahe*_*eze 7

您只想将Color延伸到安全区域,因此只需ignoresSafeAreaColor. 另外,如果您使用的是 iOS 14+,则应该使用West1 所说的ignoresSafeArea(_:edges:)弃用的。edgesIgnoringSafeArea(_:)

VStack {
    Text("Foo")
}
.background(
    Color.red.ignoresSafeArea()
)
Run Code Online (Sandbox Code Playgroud)

完整示例:

struct ContentView: View {
    var body: some View {
        VStack {
            HStack {
                Text("Foo")
                Spacer()
            }
            Spacer()
        }
        .background(
            Color.red.ignoresSafeArea() /// `edgesIgnoringSafeArea` is deprecated
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

红色背景延伸到安全区域,但文本没有延伸到安全区域