Cal*_*ter 4 opacity tabview swift swiftui
SwiftUI 中的视图默认具有透明背景。这通常意味着它们具有白色背景,因为这是应用程序的默认背景颜色。但是,这也意味着您可以使用 aZStack
来更改整个应用程序的背景颜色,并且该颜色将显示在所有视图中,除非您明确设置自己的背景颜色:
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") })
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,这对于以下情况来说并非如此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")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
块TabView
背景颜色:
我可以更改子视图的背景颜色,但如果我将其设置为透明,则背景再次变为白色,而不是显示ZStack
. 我还尝试了各种其他方法来使TabView
透明,例如将其背景设置为Color.clear
,但无济于事。
长话短说
是否可以制作TabView
透明而不是白色?
每个选项卡的托管视图都有系统背景色(不透明)。
这是可能的解决方法。使用 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")
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2276 次 |
最近记录: |