1

I want for my view model to have state to bind not in main view.

In the code below, I Binded view model's @GestureState variable to DragGesture in my main view. But the problem is, without any compile error, it does not updating my @GestureState variable at all. If I define the @GestureState variable in my main view, it work. Any idea?

class ViewModel {
    @GestureState var dragOffset = CGSize.zero
}

struct ExampleView: View {
    var viewModel = ViewModel()

    var body: some View {
        Image(systemName: "star.circle.fill")
            .font(.system(size: 100))
            .offset(x: viewModel.dragOffset.width, y: viewModel.dragOffset.height)
            .animation(.easeInOut)
            .foregroundColor(.green)
            .gesture(
                DragGesture()
                    .updating(viewModel.$dragOffset, body: { (value, state, transaction) in
                        print(state)
                        state = value.translation
                        print(state)
                    })
            )
    }
}
Jex Jang
  • 567
  • 1
  • 4
  • 9
  • `@GestureState` is by design *view-only-temporary-state*, you can't use it outside of context of activate gesture. If you want persistency, you need to use either `@State` or `@Published`. See [official documentation](https://developer.apple.com/documentation/swiftui/gestures/adding_interactivity_with_gestures) for details. – Asperi Jan 26 '20 at 12:27
  • 1
    @Asperi Thank you for your comment. How did you know it is by design view-only-temporary-state? Couldn't get a clue from the documentation you gave me. – Jex Jang Jan 26 '20 at 12:53

0 Answers0