默认情况下,SwiftUI中的视图具有透明背景。这通常意味着它们具有白色背景,因为这是您应用程序的默认背景色。但是,这也意味着您可以使用ZStack
来更改整个应用程序的背景色,除非您明确设置自己的背景色,否则该色将在所有视图中显示:
struct Main: View {
var body: some View {
ZStack {
Color.orange.edgesIgnoringSafeArea(.all)
// Sub-view inlined
VStack {
Text("Hello World")
Button("Press Me", action: { print("Pressed") })
}
}
}
}
我遇到的问题是TabView
并非如此:
struct Main: View {
var body: some View {
ZStack {
Color.orange.edgesIgnoringSafeArea(.all)
// Sub-view inlined
TabView {
VStack {
Text("Hello World")
Button("Press Me", action: { print("Pressed") })
}.tabItem {
Text("First Page")
}
}
}
}
}
TabView
会阻止背景颜色:
我可以更改子视图的背景颜色,但是如果将其设为透明,则背景将再次变为白色,而不是在ZStack
中显示基础颜色。我还尝试了其他各种方法来使TabView
透明,例如将其背景设置为Color.clear
,但无济于事。
TL; DR
是否可以使TabView
透明而不是白色?
答案 0 :(得分:1)
每个标签的托管视图具有系统背景色(不透明)。
这里是可能的解决方法。经过Xcode 12 / iOS 14的测试
struct BackgroundHelper: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView()
DispatchQueue.main.async {
// find first superview with color and make it transparent
var parent = view.superview
repeat {
if parent?.backgroundColor != nil {
parent?.backgroundColor = UIColor.clear
break
}
parent = parent?.superview
} while (parent != nil)
}
return view
}
func updateUIView(_ uiView: UIView, context: Context) {}
}
struct ContentView: View {
var body: some View {
ZStack {
Color.orange.edgesIgnoringSafeArea(.all)
// Sub-view inlined
TabView {
VStack {
Text("Hello World")
Button("Press Me", action: { print("Pressed") })
}
.background(BackgroundHelper()) // add to each tab if needed
.tabItem {
Text("First Page")
}
Text("Second")
.background(BackgroundHelper()) // add to each tab if needed
.tabItem {
Text("Second Page")
}
}
}
}
}