How to add drag/drop support to a view while making the drag preview the same as the view being dragged

25 Views Asked by At

I'm trying to implement a drag/drop to reorder function on a SwiftUI view (without using List). I'm playing around with .draggable, but I'm not sure how to implement drag/drop such that the drag preview looks the same as the view being dragged. You can see below the code that the drag preview has an abnormal shape:

@State private var items: [Color] = [.red, .blue, .green, .orange, .purple]

var body: some View {
  VStack(spacing: 16) {
    ForEach(items, id: \.self) { color in
      color
        .frame(height: 100)
        .draggable(color) {
          color
            .frame(height: 100)
        }
    }
  }
  .padding()
}

enter image description here

I have implemented the suggestion outlined in this post but that seemingly interfered with the drag/drop behavior.

Interested if this is possible.

1

There are 1 best solutions below

1
Torke On

I added a GeometryReader and then took that to calculate the size of the Preview.

VStack(spacing: 16) {
    ForEach(items, id: \.self) { color in
        GeometryReader { geo in
            color
                .frame(height: 100)
                .draggable(color) {
                    color
                        .frame(width: geo.size.width, height: geo.size.height)
                }
        }
    }
  }

enter image description here