I have a bit of confusion on the .draggable modifier in SwiftUI. I'm playing around with the overload that lets us pass in a view for the drag preview, but I cannot figure out how the framing/layout works for this preview. Below is the code I'm messing with:
@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()
}
and here is the result:
As you can see, the preview barely takes any width, and the height is clearly much greater than the 100 height of the color in the VStack. Why is this? Is there something about the preview's context that changes the framing behavior?
Furthermore, is there a way to set the frame exactly to that of the original view? Or even more ideally, is there a way to set the preview to exactly the view of the original (in this case just the color with the same frame), so that it looks like we're dragging the original view?

It would seem the
previewof thedraggablemodifier is interfering with size of the View. My personal solution would be to simulate the dragging behavior by using a combination ofgesturesandoverlaywhile still keeping thedraggablemodifier.Here's an example based on your code. First I've declared a
structconforming toIdentifiable(to distinguish the selected one from the others) holding a color:And the View is as follows:
I've used a
LongPressGestureto simulate the prolongued tap to trigger thedraggablemodifier. I've set it to 0.3s, you can change it to fit your needs, of course.This is simply a workaround, of course. If you find a solution for the native modifier it would be better and less complicated then this. Among the issues I've found is that when dragging colors they will go behind the ones appearing below, that's why I've used the
opacity. I also tried used thezIndexbut with no luck.Here's the result:
Let me know if your liks this solution!