How do I support drag and drop on iOS using Swift?

To support drag and drop on iOS using Swift, you can utilize the UIKit framework which provides built-in support for managing drag and drop interactions. Below is a simple example demonstrating how to implement drag and drop in a Swift-based iOS application.

import UIKit class ViewController: UIViewController { @IBOutlet weak var draggableView: UIView! @IBOutlet weak var dropArea: UIView! override func viewDidLoad() { super.viewDidLoad() setupDragInteraction() setupDropInteraction() } private func setupDragInteraction() { let dragInteraction = UIDragInteraction(delegate: self) draggableView.addInteraction(dragInteraction) draggableView.isUserInteractionEnabled = true } private func setupDropInteraction() { let dropInteraction = UIDropInteraction(delegate: self) dropArea.addInteraction(dropInteraction) dropArea.isUserInteractionEnabled = true } } extension ViewController: UIDragInteractionDelegate { func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] { let itemProvider = NSItemProvider(object: "Dragged Item" as NSString) let dragItem = UIDragItem(itemProvider: itemProvider) return [dragItem] } } extension ViewController: UIDropInteractionDelegate { func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { if session.canLoadObjects(ofClass: NSString.self) { session.loadObjects(ofClass: NSString.self) { items in // Handle dropped items print("Dropped: \(items)") } } } }

iOS Swift drag and drop UIDragInteraction UIDropInteraction app development UIKit