我一直在尝试在 swiftUI 中为整个视图控制器
设置背景颜色,但我无法做到。视图不采用属性 .background颜色
。
我已经尝试使用< code >。< code>sceneDelegate中的< code>viewController的backgroundColor属性,它不接受该属性,但接受< code>foregroundColor属性。
到目前为止,我发现最有效的方法是在 ContentView 正文的顶部创建一个 ZStack,并将第一层设置为“颜色”,从而忽略安全区域。Apple 将 Color 定义为“后期绑定令牌”,无论它是什么,但它的行为类似于任何其他视图。
struct ContentView: View {
var body: some View {
ZStack {
Color.red
.edgesIgnoringSafeArea(.all)
/// Your Inner View content goes here.
VStack {
Text("Hello")
} // VStack
} // ZStack
} // body View
} // ContentView
注意:要小心内部视图中的内容,因为它可以很容易地扩展以填充整个窗口,从而用白色等覆盖背景颜色。例如,流行的NavigationView倾向于扩展到整个窗口,对我来说,它倾向于忽略其记录的. background()设置。你也可以在这里执行相同的ZStack策略。
NavigationView {
ZStack {
Color.red.edgesIgnoringSafeArea(.all)
VStack {
Text("Hello")
} // VStack
} // ZStack
} // NavigationView
如果在俯视图上使用背景修饰符(.background(Color.red)),则只需用一个新视图将该视图包裹起来,背景色为红色围绕其填充或大小。因此,您应该使用矩形()视图和Z堆栈来设置整个视图的完整背景,如果需要,可以使用.edgesIgnoringSafeArea
NavigationView {
ZStack {
Rectangle().foregroundColor(.blue).edgesIgnoringSafeArea(.all)
ScrollView {
List()
ForEach(modelExampleList) { modelExample in
Row(model: modelExample)
}
}.frame(height: 200)
}.padding(.leading, 10)
}.navigationBarTitle(Text("ModelExample List"), displayMode: .large)
}
您可以使用下面的代码来更改整个视图控制器颜色
ZStack {
Color.red
.edgesIgnoringSafeArea(.all)
}
并使用此代码来更改安全区域背景颜色
ZStack {
Color.red
}