Member-only story

SwiftUI: How to use onDrag and onDrop within Grids?

iOS 14 — Xcode 12.3

Prafulla Singh
2 min readJan 23, 2021

In this tutorial we are going to implement a onDrag and onDrop to a grid. OnDrag and OnDrop can be used reorder grid with used case in managing playlist booklist etc.

Steps:

  1. Setup Mock data:
struct Grid: Identifiable {        
var id = UUID().uuidString
var gridText: String
}
class GridViewModel: ObservableObject {
@Published var gridItems =
[Grid(gridText: "Grid 1"),
Grid(gridText: "grid 2"),
Grid(gridText: "grid 3"),
Grid(gridText: "grid 4"),
Grid(gridText: "grid 5"),
Grid(gridText: "grid 6"),
Grid(gridText: "grid 7"),
Grid(gridText: "grid 8"),
Grid(gridText: "grid 9"),
Grid(gridText: "grid 10"),
Grid(gridText: "grid 11")]
@Published var currentGrid: Grid? //to keep track of dragged element
}

2 .Create a simple grid view

struct ContentView: View {
@StateObject var gridData = GridViewModel()
let columns = Array(repeating: GridItem(.flexible(), spacing: 10), count: 2)
var body: some View {
VStack{
ScrollView{…

--

--

Prafulla Singh
Prafulla Singh

No responses yet