SwiftUI : Draggable and dropDestination (Part 1)

Menura Wijesekara
2 min readJul 8, 2024

--

Drag and drop is a very usual functionality in today apps. In SwiftUI it is very easy to implement this functionality using the inbuilt .draggable and .dropDestination. This is just one method we can use to implement this functionality. Lets see how we can implement the the drag functionality.

struct dragGesture: View {

@State var names : [String] = ["Ann","Sam","Tom","Emma"]


var body: some View {
VStack{
ZStack{
Rectangle()
.frame(height: 300)
.foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
VStack{
ForEach(names,id: \.self){
i in
Text("\(i)")
.padding(10)
.draggable(i)
}
}
}
}
}

}

The dragGesture view displays a vertical list of names ("Ann", "Sam", "Tom", "Emma") on top of a blue rectangle background. Each name is displayed in a Text view with padding and is draggable. The names are arranged vertically inside a VStack, which is overlaid on the blue rectangle using a ZStack. In this code, the draggable(_:) function is applied to each Text view inside the ForEach loop. The argument i is the content of the Text view, which is one of the strings from the names array ("Ann", "Sam", "Tom", "Emma").

What Does .draggable do

  • Making the View Draggable: The draggable(_:) function makes the Text view draggable, meaning the user can press and hold on the Text view to pick it up and move it around.
  • Drag Item: The argument i specifies the data that is associated with the drag operation. In this case, it is a string from the names array. When the user drags the Text view, the string value is encapsulated in a NSItemProvider and used as the drag item.
  • Default Drag Behaviour: By default, the drag item will be the textual representation of the string (i.e., the name itself), and it will be represented visually during the drag operation.

This is how we can use the .draggable in our code to make the components in the UI draggable. You can replace the component in the code and make any component draggable within the UI. Hope you got a better understanding about the .draggable in SwiftUI. Let’s meet in the next blog to understand about the .dropDestination part. Till that Happy Coding….

--

--