Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does swiftui have a hitTest equivalent?

Tags:

swiftui

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?

like image 404
thekodols Avatar asked Jun 10 '19 21:06

thekodols


People also ask

Why is it so hard to unit test SwiftUI?

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.

How do I create a UI Test in SwiftUI?

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:

What is the difference between SwiftUI and UIKit?

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.

Are view models easier to test than views in SwiftUI?

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?


2 Answers

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.

like image 78
Asperi Avatar answered Oct 19 '22 03:10

Asperi


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)
                }
       )
like image 2
joliejuly Avatar answered Oct 19 '22 03:10

joliejuly