skip to Main Content

Do you know how I can achieve a drag and drop result like in the "reminders" app from Apple using SwiftUI? If not, how could I do a UIViewRepresentable (from UIKit) for a Drag and Drop feature with UIKit for SwiftUI?

Please see the picture below.

Any suggestions would be greatly appreciated.

enter image description here

2

Answers


  1. This tutorial has everything you need and it is very easy to follow up.
    (As a side note, SwiftUI makes it indeed easy as opposed to how one has to do it in UIKit).

    https://www.vadimbulavin.com/add-edit-move-and-drag-and-drop-in-swiftui-list/

    Update:
    I add some explanations on how to resolve the issue.

    Steps:

    1. Add a handler for .onInsert() on your list,
    2. Implement that handler.

    The handler signature is (Int, [NSItemProvider]), which provides you the index where the dragged object is dropped, and itemProviders which provide you with info on what has been dropped.

    struct EditListView: View {
       @State private var items: [Item] = [
          Item(title: "Apple"),
          Item(title: "Banana"),
          Item(title: "Papaya"),
          Item(title: "Mango")
       ]
       
       var body: some View {
          NavigationView{
             List {
                ForEach(
                   items,
                   id: .self
                ) { item in
                   Text(item.title)
                }
                .onInsert(of: [String(kUTTypeURL)], perform: onInsert)
             }
             .navigationTitle("Fruits")
    
          }
       }
       
       private func onInsert(at offset: Int, itemProvider: [NSItemProvider]) {
          for provider in itemProvider {
            // check if object is of URL type 
             if provider.canLoadObject(ofClass: URL.self) {
                // load the object and add it on screen
                _ = provider.loadObject(ofClass: URL.self) { url, error in
                   DispatchQueue.main.async {
                      url.map { self.items.insert(Item(title: $0.absoluteString), at: offset) }
                   }
                }
             }
          }
       }
       
    }
    
    Login or Signup to reply.
  2. So far there is not really a boot in method to drag and drop. The .onDrag modifier really only seems to work on the iPad. My suggestion is that you use a UIViewRepresentable and make a table view (UI kit) and then implement the drag and drop from there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search