简体   繁体   English

在列表 SwiftUI 中拖放以移动行

[英]Drag and drop to move row in List SwiftUI

I'm working with List in SwiftUI.我正在 SwiftUI 中使用 List。 I want to add feature of drag and drop row(items) in List.我想在列表中添加拖放行(项目)的功能。 In Swift we have UITableView's Delegate and DataSource methods like below:在 Swift 中,我们有 UITableView 的 Delegate 和 DataSource 方法,如下所示:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;

What is the alternative of these method in SwiftUI? SwiftUI 中这些方法的替代方法是什么?

struct User {
    var firstName: String
    var lastName: String
}

struct UserRow: View {
    var user: User

    var body: some View {
        Text("\(user.firstName) \(user.lastName)")
    }
}

struct ContentView : View {
    var body: some View {

        let user1 = User(firstName: "Anjali", lastName: "User1")
        let user2 = User(firstName: "XYZ", lastName: "User2")

        return List {
            UserRow(user: user1)
            UserRow(user: user2)
        }
    }
}

In the WWDC there is a video that explain briefly how to activate edit mode on a list and how to move items.在 WWDC 中有一段视频简要解释了如何在列表上激活编辑模式以及如何移动项目。

You can use the onMove modifier to handle cell reordering, and the EditButton() to activate the edit mode, which allows you to move cells manually.您可以使用onMove修饰符来处理单元格重新排序,并使用EditButton()激活编辑模式,这允许您手动移动单元格。

Note that you can't use the onMove method on a static list.请注意,您不能在静态列表上使用onMove方法。 This modifier is available in the DynamicViewContent protocol, which is implemented by ForEach , but not by List .此修饰符在DynamicViewContent协议中可用,该协议由ForEach实现,但不是由List

struct ContentView : View {
    let users = [
        User(firstName: "Anjali", lastName: "User1"),
        User(firstName: "XYZ", lastName: "User2")
    ]

    var body: some View {
        NavigationView {
            List {
                ForEach(users.identified(by: \.firstName)) { user in
                    UserRow(user: user)
                }.onMove(perform: move)
            }
            .navigationBarTitle(Text("Users"))
            .navigationBarItems(trailing: EditButton())
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        users.move(fromOffsets: source, toOffset: destination)
    }
}

To make it always draggable without EditButton just add this modifier to your List:要使其在没有EditButton情况下始终可拖动,只需将此修饰符添加到您的列表中:

.environment(\.editMode, Binding.constant(EditMode.active))

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

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