Skip to content

Instantly share code, notes, and snippets.

@ryohey
Created July 21, 2023 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryohey/eb5b39feb240c3326d21fa2d4c4bd2b3 to your computer and use it in GitHub Desktop.
Save ryohey/eb5b39feb240c3326d21fa2d4c4bd2b3 to your computer and use it in GitHub Desktop.
SwiftUI Custom Extension: Precise onTapGesture. This extension to SwiftUI's onTapGesture method addresses the default behavior where the tap recognition area slightly extends beyond the View's actual drawn bounds. With this extension, taps are accurately recognized only within the exact bounds of the View, ensuring more precise user interaction.
import SwiftUI
extension View {
/**
* This is a custom extension to SwiftUI's onTapGesture, designed to avoid the issue where the tappable area extends slightly beyond the view's drawing bounds.
* Unlike the original onTapGesture, this version ensures the tap is only recognized within the exact drawing bounds of the View.
*/
func onTapGestureExact(_ action: @escaping (CGPoint) -> Void) -> some View {
overlay {
GeometryReader { proxy in
Color.clear
.contentShape(Rectangle())
.onTapGesture { location in
if location.x >= 0,
location.y >= 0,
location.x < proxy.size.width,
location.y < proxy.size.height {
action(location)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment