SwiftUI: VStack/HStack/ZStack drag gesture not working

Actually, there's a SwiftUI feature meant to address just that issue with no need for a background.

Simply place .contentShape(Rectangle()) just before your gesture modifier and it will respond to the whole enclosing rectangle. :)


Your container is transparent. Transparent thing does not handle events. So, add some background, like in demo below and all works.

var body: some View {
    VStack {
        Text("Hello World!")
    }
    .frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
    .edgesIgnoringSafeArea(.all)
    .background(Color.white)
    .offset(y: offset.height)
    .gesture(DragGesture()
        .onChanged { val in
            self.offset = val.translation
        }
        .onEnded { val in
            self.offset = .zero
        }
    )
}

Tags:

Ios

Swift

Swiftui