skip to Main Content

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.

2

Answers


  1. The issue you’re encountering is likely due to the way the ScrollView and Button are structured in your layout. Specifically, the problem may arise because the Button is inside a ZStack, and its hit area might be constrained or overlapped by other views.

    struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            ScrollView(.horizontal) {
                HStack {
                    Button(action: {
                        print("Button clicked")
                    }) {
                        Text("Button")
                            .foregroundColor(.white)
                            .padding(8)
                            .background(Color.green)
                            .cornerRadius(8)
                            .contentShape(Rectangle()) // Ensure the entire area is clickable
                    }
                    .frame(height: 40) // Set a clear frame for the button
                }
            }
            .background(Color.blue)
            .frame(height: 40)
            
            TabView {
                ZStack {
                    Color.yellow
                    Text("my view")
                }
            }
        }
    }
    

    }

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search