首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在swiftui中的列表行上拖放

在swiftui中的列表行上拖放
EN

Stack Overflow用户
提问于 2021-11-11 16:35:44
回答 1查看 357关注 0票数 2

我一直在尝试在SwiftUI中的List上实现拖放。我要做的就是在List上拖一行,然后放到同一个List中的一行上,就像iOS上的Remainders应用程序一样。

注意:重要的是要注意,我并不是要重新排列列表,而是要使被删除的项成为该行的“子”项。

代码语言:javascript
运行
复制
import SwiftUI
import UniformTypeIdentifiers

struct Item: Identifiable {
    let id = UUID()
    let title: String
}

struct EditListView: View {
   @State private var items: [Item] = [
      Item(title: "Apple"),
      Item(title: "Banana"),
      Item(title: "Papaya"),
      Item(title: "Mango")
   ]
   
   var body: some View {
      
       VStack {
         List {
            ForEach(items) { item in
               Text(item.title)
            }
            .onDrop(of: [UTType.text], delegate:dropDelegate() )//doesn't work
            
            .onDrag{
                NSItemProvider(item: .some(URL(string: "item")! as NSSecureCoding), typeIdentifier: String() )
            }
         }
           
        Text("Drop Item Here..")
               .fontWeight(.heavy) 
               .onDrop(of: [UTType.text], delegate:dropDelegate() )//works
        
       }
   }
}


class dropDelegate: DropDelegate {

    func performDrop(info: DropInfo) -> Bool {
        print("drop success")
        return true
    }
}

使用Text是可行的。

在列表行上拖放失败。

EN

回答 1

Stack Overflow用户

发布于 2021-11-19 14:01:39

看起来你的代码有两个问题。

First:web上的许多文章报告说,drop在List组件上不起作用,但您可以用ScrollView替换List。然后将调用drop方法。

第二个:如果你想逐项应用一个action,你必须将drop方法移到foreach中。

在更新后的代码中,我刚刚添加了一个单元格样本,你可以很容易地自己重现一个单元格效果:

代码语言:javascript
运行
复制
struct Sample: View {
    @State private var items: [Item] = [
        Item(title: "Apple"),
        Item(title: "Banana"),
        Item(title: "Papaya"),
        Item(title: "Mango")
    ]

    var body: some View {
        VStack {
            ScrollView {
                ForEach(items) { item in
                    SampleCell(item: item)
                        .onDrop(of: [UTType.text], delegate:dropDelegate() )
                        .onDrag{
                            NSItemProvider(item: .some(URL(string: "item")! as NSSecureCoding), typeIdentifier: String() )
                        }
                }
            }
            Text("Drop Item Here..")
                .fontWeight(.heavy)
                .onDrop(of: [UTType.text], delegate:dropDelegate() )//works

        }
    }
}

struct SampleCell: View {
    var item : Item
    var body: some View {
        HStack {
            Text(item.title).padding()
            Spacer()
        }.frame(maxWidth:.infinity, minHeight: 60)
        .background(Color.gray)
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69931818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档