SwiftUI: How to get drag and drop reordering of items to work? SwiftUI: How to get drag and drop reordering of items to work? swift swift

SwiftUI: How to get drag and drop reordering of items to work?


According to Apple reply in Drag and Drop to reorder Items using the new LazyGrids?

That's not built-today, though you can use the View.onDrag(_:) andView.onDrop(...) to add support for drag and drop manually.

Do file a feedback request if you'd like to see built-in reorderingsupport. Thanks!

So the solution using .onDrag & .onDrop provided in my answer for actually duplicated question in https://stackoverflow.com/a/63438481/12299030

Main idea is to track drug & drop by grid card views and reorder model in drop delegate, so LazyVGrid animates subviews:

   LazyVGrid(columns: model.columns, spacing: 32) {        ForEach(model.data) { d in            GridItemView(d: d)                .overlay(dragging?.id == d.id ? Color.white.opacity(0.8) : Color.clear)                .onDrag {                    self.dragging = d                    return NSItemProvider(object: String(d.id) as NSString)                }                .onDrop(of: [UTType.text], delegate: DragRelocateDelegate(item: d, listData: $model.data, current: $dragging))        }    }.animation(.default, value: model.data)

...

    func dropEntered(info: DropInfo) {        if item != current {            let from = listData.firstIndex(of: current!)!            let to = listData.firstIndex(of: item)!            if listData[to].id != current!.id {                listData.move(fromOffsets: IndexSet(integer: from),                    toOffset: to > from ? to + 1 : to)            }        }    }


You can use a List and hide the separators.

.onAppear { UITableView.appearance().separatorStyle = .none}