Search code examples
iosswiftswiftuiswiftui-tabviewswiftui-scrollview

Swiftui Bug - Button (only top part is clickable)


I'm having an issue with SwiftUI where only the top part of the button is clickable, while the bottom part is not clickable at all.

Here is my code snippet. Does anyone know how I can fix this?

struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            ScrollView(.horizontal) {
                HStack {
                    Button(action: {}, label: {
                        ZStack {
                            Color.green
                            Text("Button")
                                .padding(8)
                                .contentShape(Rectangle())
                        }
                    })
                }
            }
            .background(Color.blue)
            .frame(height: 40)
            
            TabView {
                ZStack {
                    Color.yellow
                    Text("my view")
                }
            }
        }
    }
}

I have tried to change the VStack to ZStack, or introduce the Zindex but it isn't helped. The issue is happening with the combination of ScrollView + TabView.


Solution

  • I don't work with SwiftUI (only played with it a bit) but after some quick searching...

    It appears TabView has an extended "hit-test" area at the top.

    For your layout, add a .contentShape modifier:

            TabView {
                ZStack {
                    Color.yellow
                    Text("my view")
                }
            }
            .contentShape(Rectangle())    // <-- should fix the issue