简体   繁体   中英

SwiftUI Drag and Drop with a list

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.

在此处输入图像描述

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.

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) }
               }
            }
         }
      }
   }
   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM