Created
July 21, 2023 05:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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