Constrain View while using DragGesture in SwiftUI

86 Views Asked by At

I am currently building a BeReal clone and I am working on the small picture you can drag across the screen.

Rectangle Code (Placeholder for small image)

Rectangle()
    .frame(width: UIScreen.main.bounds.width * 0.33,
           height: UIScreen.main.bounds.width * 0.44)
    .offset(smallOffset)
    .gesture(
        DragGesture()
            .onChanged({ changedValue in
                smallOffset = changedValue.translation
            })
            .onEnded({ _ in
                smallOffset = .zero
            })
    )
    .animation(.easeIn, value: 200)

Frame for ZStack

@State var smallOffset: CGSize = .zero

var body: some View{
    ZStack{
        ....
    }
    .frame(width: UIScreen.main.bounds.width,
           height: UIScreen.main.bounds.width * 1.33)
}

The Drag Gesture is working, but it is allowed to go over the frame I have given. So is there any way I can prevent the rectangle to go over the frame I set for the entire ZStack

Essentially I want the Rectangle to disappear behind the rest of the things on the screen when it leaves the given frame

0

There are 0 best solutions below