拖放列表以在SwiftUI上重新排序

时间:2019-06-27 11:59:21

标签: swiftui

如何添加拖放以重新排序列表中的行? 只是没有“编辑模式”的干净解决方案。

2 个答案:

答案 0 :(得分:1)

要在用户长按项目时将列表置于编辑模式,可以使用状态标志并相应地设置编辑环境值。重要的是,将标志更改动画化,以免显得很怪异。

struct ContentView: View {
    @State private var fruits = ["Apple", "Banana", "Mango"]
    @State private var isEditable = false

    var body: some View {
        List {
            ForEach(fruits, id: \.self) { user in
                Text(user)
            }
            .onMove(perform: move)
            .onLongPressGesture {
                withAnimation {
                    self.isEditable = true
                }
            }
        }
        .environment(\.editMode, isEditable ? .constant(.active) : .constant(.inactive))
    }

    func move(from source: IndexSet, to destination: Int) {
        fruits.move(fromOffsets: source, toOffset: destination)
        withAnimation {
            isEditable = false
        }
    }
}

答案 1 :(得分:0)

https://www.hackingwithswift.com/quick-start/swiftui/how-to-let-users-move-rows-in-a-list

上有一篇很好的文章。

我不想直接在此处复制粘贴Paul's代码,因此这是我用略有不同的结构写的另一个示例。

import SwiftUI

struct ReorderingView: View {

  @State private var items = Array((0...10))

  var body: some View {
    NavigationView {
      VStack {
        List {
          ForEach(items) { item in
              Text("\(item)")
          }.onMove { (source: IndexSet, destination: Int) -> Void in
            self.items.move(fromOffsets: source, toOffset: destination)
          }
        }
      }
      //.environment(\.editMode, .constant(.active)) // use this to keep it editable always
      .navigationBarItems(trailing: EditButton()) // can replace with the above
      .navigationBarTitle("Reorder")
    }
  }
}

struct ReorderingView_Previews: PreviewProvider {
  static var previews: some View {
    ReorderingView()
  }
}

extension Int: Identifiable { // Please don't use this in production
  public var id: Int { return self }
}