Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Increase tap/drag area for user interaction

Tags:

swift

swiftui

I've built a custom slider in SwiftUI with a thumb dragger that is 20x20. Everything is working, except the tap target is quite small since it's just the 20x20 view. I'm looking for a way to increase this to make it easier for users to interact with my slider. Is there a way to do this in SwiftUI?

I tried wrapping my thumb in Color.clear.overlay and setting the frame to 60x60. This works if the color is solid, like red, but with clear the tap target seems to revert back to visible pixels of 20x20.

You can see on this gif I'm able to drag the slider even when clicking outside of the thumb.

slider with red background

However, as soon as I change the color to clear, this area no longer receives interactions.

slider with clear background

like image 496
keegan3d Avatar asked Jul 29 '19 17:07

keegan3d


3 Answers

Add a .contentShape(Rectangle()) after the frame.

like image 183
Joris Kluivers Avatar answered Oct 13 '22 23:10

Joris Kluivers


I'm sure there are several ways to accomplish this, but this is how i made a big button with the whole area tappable:

Button(action: { someAction() }, label: {
                Text("OK")
                .frame(minWidth: 200)
                .contentShape(Rectangle())
                .padding()
            })
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(5.0)
like image 42
Chris Avatar answered Oct 13 '22 22:10

Chris


I had the same problem. Except I didn't want the expanded overlay to impact the rest of the layout. If you embed everything in a ZStack and put a rectangle before your interactive object, you can control the size of the gesture. Kind of like this:

Rectangle().frame(width: screen.width, height: 300).opacity(0.001)
                    .layoutPriority(-1)

Just needed to make sure to set the opacity to next to nothing so you can't see it, and the layout priority to -1 so it doesn't impact the view.

like image 3
Ben E. Avatar answered Oct 13 '22 22:10

Ben E.