I have a gesture's touch location in global coordinate space from which I'd like to figure out the Rectangle that's at those coordinates. How can I do that?
That task might become especially tricky when working with SwiftUI, as so much of our UI-centric logic tends to wind up within our various View declarations, which in turn often makes such code really difficult to verify using unit tests.
Let's first create an app in SwiftUI. If you don't have any UI testing target, please create one by doing Command + 6 or Select Test Navigator . It should look something like so:
Unlike UIKit, which is commonly used in conjunction with storyboards, SwiftUI is completely software-based. However, SwiftUI syntax is very easy to understand, and a SwiftUI project can be quickly viewed using Automatic Preview.
So, regardless of whether we choose to go for a view model, a simple model extension, or another kind of metaphor — if we can move the UI logic that we’re looking to test out from our views themselves, then those tests tend to be much easier to write and maintain. So, how do I unit test my SwiftUI views?
No it does not. By SwiftUI design one should explicitly add tap gesture to a view which is going to handle action. So, if my view would have some tappable elements I have to make them as view and attach gesture to it, like
var body: some View {
HStack {
Rectangle()
.fill(Color.red.opacity(0.2))
.frame(width: 300, height: 300)
.clipShape(Circle())
.onTapGesture {
print("Tapped!")
}
}
}
If some views can overlap then inactive view should be marked with .allowsHitTesting(false) modifier.
There is a .allowsHitTesting(_:)
modifier which can be used to control whether a view should recognize touches.
https://developer.apple.com/documentation/swiftui/view/allowshittesting(_:)
To obtain an exact location of a tap, you can use a drag gesture recognizer with zero distance:
Rectangle()
.gesture(
DragGesture(minimumDistance: 0)
.onEnded { value in
let location = value.location
print(location)
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With