make a ondrag function for a rectangle that returns the string "yellow" in swift in swiftui in swift

You can create a Rectangle view in SwiftUI and use its modifier onDrag to enable the dragging functionality. The onDrag modifier needs to return an instance of NSItemProvider that will be used to transfer data from drag source to drop destination.

Here's the code to make a Rectangle draggable and return "yellow" string:

main.swift
struct DraggableRectangle: View {

    let itemProvider = NSItemProvider(object: "yellow" as NSString)

    var body: some View {
        Rectangle()
            .fill(Color.yellow)
            .frame(width: 100, height: 100)
            .onDrag { self.itemProvider }
    }
}
276 chars
12 lines

You can use this DraggableRectangle view inside any SwiftUI container to make it draggable.

Note that the onDrag closure captures the self.itemProvider property and returns it. So when a drag gesture is detected on this view, self.itemProvider will be used to provide the data (in this case, the string "yellow") to the system's drag and drop APIs.

related categories

gistlibby LogSnag