SwiftUI: how do I drag multiple items separately with the onDrag gesture?

729 Views Asked by At

So I've been playing around in Xcode. And I have a question. The problem is that when I use the dragGesture and I put multiple items (in this case Rectangles) on the screen, all of them move when I want to just move one item.

I want to move all the items separately. How do i do that?

Here is de code I wrote:


import SwiftUI

struct GameView: View {
    
    @State var offset: CGSize = .zero
   
    var body: some View {
        ZStack{
            Image("Wolffront")
            
            VStack(spacing: 10){
                Rectangle()
                    .fill(.green)
                    .frame(width: 50, height: 50)
                    .cornerRadius(10)
                    .shadow(color: .black, radius: 10, x: 10, y: 10)
                    .navigationBarHidden(true)
                    .overlay(
                    Text("O")
                        .font(.largeTitle)
                        .foregroundColor(.white)
                    )
                    .offset(offset)
                    .gesture(DragGesture()
                                .onChanged { value in
                        withAnimation(.spring()) {
                            offset = value.translation
                                
                        }
                    }
                                .onEnded {value in
                        withAnimation(.spring()) {
                            offset = value .translation
                        }
                    }
                    )
                
                    Rectangle()
                        .fill(.green)
                        .frame(width: 50, height: 50)
                        .cornerRadius(10)
                        .shadow(color: .black, radius: 10, x: 10, y: 10)
                        .navigationBarHidden(true)
                        .overlay(
                        Text("O")
                            .font(.largeTitle)
                            .foregroundColor(.white)
                        )
                        .offset(offset)
                        .gesture(DragGesture()
                                    .onChanged { value in
                            withAnimation(.spring()) {
                                offset = value.translation
                                    
                            }
                        }
                                    .onEnded {value in
                            withAnimation(.spring()) {
                                offset = value .translation
                            }
                        }
                        )
                
            }
            
    }
        
}
}
    
struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView()
    }
}
0

There are 0 best solutions below