【问题标题】:How can I move List Items without having to toggle EditMode如何在不切换 EditMode 的情况下移动列表项
【发布时间】:2022-01-01 06:32:56
【问题描述】:

我目前正在 SwiftUI 中构建一个待办事项列表应用程序。我真正想要实现的一项功能是手动对列表进行排序的能力,因此我在ForEach 循环中使用.onMove 修饰符集成了该功能,填充了我的List,但我仍然需要切换手动编辑模式,所以我将列表的编辑模式设置为.active,如下:

import SwiftUI

struct ContentView: View {
@State private var items = ["1", "2", "3"]
@State var editMode: EditMode = .active

var body: some View {
    List {
        ForEach(items, id: \.self) { item in
            Text("Item \(item)")
        }
        .onMove(perform: { _, _  in })
    }
    .environment(\.editMode, $editMode)
}
}

但我对这个实现并不满意,因为我仍然必须使用 EditMode 中的手柄,而且它还破坏了 SwipeActions 以及 Button 功能。

那么如何在不使用 EditMode 的情况下移动列表项?

【问题讨论】:

  • 这是否回答了您的问题stackoverflow.com/a/58770635/12299030
  • 不是真的,因为我仍然有设置的抓取点并且启用了编辑模式会破坏按钮功能以将任务标记为已完成。 @Asperi
  • 我实际上是通过您的另一个答案找到了解决方案,与链接的帖子相关,所以谢谢! @Asperi

标签: swiftui swiftui-list


【解决方案1】:

根据 Asperi 对 this 问题的回答,我实现了拖放手势来解决该问题,如下所示:

struct ContentView: View {

@State var items = [Item(id: 1), Item(id: 2), Item(id: 3), Item(id: 4)]
@State private var dragging: Item?

var body: some View{
    List{
        ForEach(items){ item in
            Text("Item \(item.id)")
                .onDrag {
                    self.dragging = item
                    return NSItemProvider(object: NSString())
                }
                .onDrop(of: [UTType.text], delegate: DragDelegate(current: $dragging))
        }
        .onMove(perform: {_, _  in })
    }
}
}

使用DropDelegate 实现:

struct DragDelegate<Item: Equatable>: DropDelegate {
@Binding var current: Item?

func dropUpdated(info: DropInfo) -> DropProposal? {
    DropProposal(operation: .move)
}

func performDrop(info: DropInfo) -> Bool {
    current = nil
    return true
}
}

注意:项目现在必须符合 IdentifiableEquatable 所以最小的实现是:

struct Item: Identifiable, Equatable{
let id: Int
}

你还需要导入:

import UniformTypeIdentifiers

为了使用拖放功能

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多