.draggable()
The .draggable()
view modifier in SwiftUI gives a view the ability to be dragged around the user interface. It works in conjunction with the .dropDestination()
modifier which provides a destination to drop draggable views. The data type or view you wish to drag-and-drop must conform to the Transferable protocol.
Note: The data to be dragged and subsequently dropped must conform to the Transferable protocol. This ensures the data being dragged can be recognized and processed by other views or external applications. For information on protocols, see Protocols.
Syntax
View
.draggable(payload, preview)
This method has two optional parameters:
payload
: The data the view carries as it is dragged, the default value is the view itselfpreview
: The feedback you want to display to the user while they drag the view
Example
struct ContentView: View {@State private var myPayload: String = "I belong in a blue box."var body: some View {HStack(spacing: 50) {Square(text: $myPayload, color: .pink).draggable(myPayload, preview: {Text("Dragging...").padding().background(Color.purple).cornerRadius(25)})}}}struct Square: View {@Binding var text: Stringvar color: Colorvar body: some View {ZStack {colorText(text).padding().bold()}.frame(width: 150, height: 150).cornerRadius(25)}}
Note: The
Square
view is a custom view that takes two parameters:text
andcolor
. Thetext
parameter binds to themyPayload
state variable, while thecolor
parameter determines the background color of the view. For information on custom views, see Views.
In the example, the custom Square view has a .draggable()
modifier. When dragged, it carries the String
assigned to myPayload
and displays a "Dragging..."
message within a purple, rounded rectangle until it is dropped.
This will display:
Note:
.draggable()
is the first of two parts in the drag-and-drop operation. While it can be used independently, as shown here, it is usually paired with the.dropDestination()
modifier. For information on setting up a drop destination, see .dropDestination().
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SwiftUI on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours