SwiftUI 中的 View 默认具有透明背景。这通常意味着它们具有白色背景,因为这是您应用的默认背景颜色。但是,这也意味着您可以使用 ZStack
更改整个应用程序的背景颜色,除非您明确设置自己的背景颜色,否则该颜色将显示在所有 View 中:
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
阻止背景颜色:我可以改变 subview 的背景颜色,但如果我让它透明,背景又会变成白色,而不是在
ZStack
中显示底层颜色。 .我还尝试了各种其他方法来制作 TabView
透明,比如设置背景为Color.clear
,但无济于事。TL;博士
是否可以制作
TabView
透明而不是白色?
最佳答案
每个选项卡的托管 View 都有系统背景颜色(不透明)。
这是可能的解决方法。使用 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")
}
}
}
}
}
关于swift - 使 TabView 背景透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63178381/