SwiftUI Sidebar Make Extra Space Clickable

Viewed 29

I read that Spacer() does not work with onTapGesture since it requires visible/opaque views(?).

This is a snippet of my code.

         HStack {
                SideMenuView(dark: self.$dark, show: self.$show, navigationManager: navigationManager)
                    .preferredColorScheme(self.dark ? .dark : .light)
                    .offset(x: self.show ? 0 : -UIScreen.main.bounds.width / 1.2)
                Spacer(minLength:  0)
            }
            .background(Color.primary.opacity(self.show ? (self.dark ? 0.05 : 0.2) : 0).edgesIgnoringSafeArea(.all))
            .onTapGesture {
                withAnimation(.default) {
                    show.toggle()
                }
            }

What I am trying to solve is to make the extra space beside the sidebar clickable (so it can be collapsed). With the current code, everywhere in the screen that does not receive input will trigger onTapGesture (Text labels in the sidebar, extra space beside it)

Is there a view I am missing here? Or do i need to add a Rectangle() and calculate the extra space?

1 Answers

See .contentShape which allows you to specify the hit area.

Another solution I often see is using an almost clear color. Like SwiftUIX does for example Color.almostClear

Because then it will still look transparent, but be hittable

Related