Home > Mobile >  SwiftUI onTapGuesture not working using offset inside ZStack?
SwiftUI onTapGuesture not working using offset inside ZStack?

Time:09-26

I have a Mapbox map view and a search bar and activate button (HStack) inside a ZStack and using an offset modifier to position them at the top of the screen.

For some reason the offset is preventing the onTapGesture from working for the activate button, if I comment out the offset it will work but will be placed at the bottom of the screen.

I tried adding the offset to each element individually inside the HStack but that did not work...

How can I make the onTapGesture functionality work with offset?

Thank you

struct MapScreen: View {
        
    var body: some View {
        NavigationView {
            ZStack(alignment: .bottom) {
                HStack(spacing: 10) {
                    SearchBar()
                        .padding(.leading, 5)
                        .onTapGesture {
                            print("search pressed")
                           
                        }
                    ActivateButton()
                        .onTapGesture {
                            print("activate pressed")
                        }
                }.zIndex(2)
                .offset(y: -770)
                MapView(locations: $locations)
                  .edgesIgnoringSafeArea([.top, .bottom])
                BottomNavBar().zIndex(1)
                  .edgesIgnoringSafeArea(.all).offset(y: 35)
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .fullScreenCover(isPresented: $presentSearchView, content: {
                SearchView()
             })
        }
    }
}

CodePudding user response:

There's a couple problems here:

.offset(y: -770)

If you're trying to use an offset so large, you shouldn't be using offset at all. offset is usually for fine-tune adjustments and doesn't work great with big values. And also, 770 is hardcoded. What happens when you use another device with a different screen size? Don't hardcode or do calculations yourself — SwiftUI can do it for you!

Instead, use a VStack Spacer() to push the search bar up.

ZStack(alignment: .bottom) {
    VStack { /// here!
        HStack(spacing: 10) {
            SearchBar()
                .padding(.leading, 5)
                .onTapGesture {
                    print("search pressed")
                    
                }
            ActivateButton()
                .onTapGesture {
                    print("activate pressed")
                }
        }
        
        Spacer() /// push the `HStack` to the top of the screen
    }
    .zIndex(2)
    
    MapView(locations: $locations)
        .edgesIgnoringSafeArea([.top, .bottom])
    BottomNavBar().zIndex(1)
        .edgesIgnoringSafeArea(.all).offset(y: 35)
}
  • Related