简体   繁体   English

SwiftUI 用列表拖放

[英]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?您知道如何使用 SwiftUI 在 Apple 的“提醒”应用程序中实现拖放结果吗? If not, how could I do a UIViewRepresentable (from UIKit) for a Drag and Drop feature with UIKit for SwiftUI?如果没有,我怎么能用 UIKit 为 SwiftUI 做一个 UIViewRepresentable(来自 UIKit)的拖放功能?

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. .onDrag 修饰符似乎只适用于 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.我的建议是您使用 UIViewRepresentable 并制作一个表格视图(UI 工具包),然后从那里实现拖放。

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). (作为旁注,SwiftUI 确实很容易,而不是在 UIKit 中必须这样做)。

https://www.vadimbulavin.com/add-edit-move-and-drag-and-drop-in-swiftui-list/ 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,在您的列表中添加一个处理程序 for.onInsert(),
  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.处理程序签名是(Int, [NSItemProvider]) ,它为您提供拖放的itemProvidersindex ,以及为您提供有关已删除内容的信息的 itemProviders。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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