touchesMoved in SwiftUI?

Hi,


Is there an equivalent to UIKit's `touchesBegan`, `touchesMoved`, etc., in SwiftUI?


If I want to create an advanced custom view, with the exact kind of interaction that I envision, in UIKit I'd implement `touchesMoved` and friends, keep some state machine in my view, and draw things in `drawRect`. I understand that in SwiftUI you can replace `drawRect` with `Shape`s. But what about the low level touch handling?

Replies

Look at the @GestureState property wrapper. This allows you to bind the state of a drag gesture into a property whose value can then be used to drive layout of the UI. A simple use for this is to use it along with a GeometryReader to get a coordinate for the gesture's current point anchor to put a moveable view at a specific coordinate on the screen. I'll see if I can code up a quick example & post it here.

As promised, here's a sample:


import SwiftUI

struct ContentView: View {
    @GestureState var translation: CGSize = .zero
    
    var body: some View {
        Circle()
            .fill(Color.blue)
            .frame(width: 100, height: 100)
            .offset(translation)
            .gesture(DragGesture().updating($translation) { value, state, _ in
                state = value.translation
            })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}