使 TabView 背景透明

Make TabView Background Transparent

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 透明而不是白色?

每个选项卡的托管视图都有系统背景颜色(不透明)。

这是可能的解决方法。测试 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")
                    }
            }
        }
    }
}