Drag gesture not working when using a function returning a View

Viewed 203

I have a View with an element that has drag gesture, which is working fine. However, I am trying to use a modifier function to put the whole thing in a ZStack and present something else on top of it as well optionally. If I use the additionalView modifier, the drag gesture stops working. I even tried to use it with an EmptyView(), and also tried to return just body within additionalView, the drag gesture was not working. For some reason the translation variable is not updating in DragGesture.updating however value has the correct value. Tried also to use @State instead of @GestureState and update it manually, that didn't work either. Maybe not using a function for presenting an optional view but using an optional @ViewBuilder parameter in the view's constructor and put the ZStack in body would do the trick, but I like more this approach.

struct DragTest: View {
    @GestureState private var translation: CGFloat = 0
    var body: some View {
        GeometryReader { geometry in
            HStack(spacing: 0) {
                Spacer()
                Text("some text")
                Spacer()
            }
            .frame(width: geometry.size.width, alignment: .leading)
            .offset(x: self.translation)
            .gesture(
                DragGesture().updating(self.$translation) { value, state, _ in
                    state = value.translation.width
                    print(value.translation.width)
                    print(self.translation)
                }
            )
        }
    }

    func additionalView<AdditionalView: View>(@ViewBuilder additionalView: @escaping () -> AdditionalView) -> some View {
        ZStack {
            self.body
            additionalView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        DragTest()
            .additionalView {
                EmptyView()
        }
    }
}
0 Answers
Related