Two view modifiers give an app drag and drop: draggable marks a view as a drag source, and
dropDestination marks a view as a drop target. Both move any type that conforms to
Transferable, the same protocol behind ShareLink.
Dragging
Attach draggable with the value to move. Types such as URL conform to Transferable
already, so no conversion code is needed. The trailing closure supplies the drag preview.
List {
ForEach(links, id: \.self) { url in
Text(url.absoluteString)
.draggable(url) {
Text(verbatim: url.absoluteString)
}
}
}
Any custom type works the same way once it conforms to Transferable. See the sharing-content
doc in this area for the conformance recipe.
Dropping
dropDestination(for:) registers the area that accepts drops of one transferable type. The
handler receives the decoded items and the drop location on screen.
List {
ForEach(links, id: \.self) { url in
Text(url.absoluteString)
.draggable(url) { Text(verbatim: url.absoluteString) }
}
.dropDestination(for: URL.self) { items, location in
links.append(contentsOf: items)
}
}
The items parameter is an array because one drop can carry several values. The location
parameter is the point where the user released the drag, useful for positioning inserted
content.