Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Table Custom Swipe?

Tags:

swift

swiftui

Is there a way to swipe table rows to the left and to the right? I haven't found something for the new Framework SwiftUI so maybe there is no chance to use SwiftUI for this? I need to delete rows and use custom Swipes

like image 400
Max Avatar asked Jun 26 '19 18:06

Max


1 Answers

It is possible to implement a delete action and the ability to reorder list items quite simply.

struct SwipeActionView: View {
    @State var items: [String] = ["One", "two", "three", "four"]

    var body: some View {
        NavigationView {
            List {
                ForEach(items.identified(by: \.self)) { item in
                    Text(item)
                }
                .onMove(perform: move)
                .onDelete(perform: delete)      
            }
            .navigationBarItems(trailing: EditButton())
        }
    }

    func delete(at offsets: IndexSet) {
        if let first = offsets.first {
            items.remove(at: first)
        }
    }

    func move(from source: IndexSet, to destination: Int) {
        // sort the indexes low to high
        let reversedSource = source.sorted()

        // then loop from the back to avoid reordering problems
        for index in reversedSource.reversed() {
            // for each item, remove it and insert it at the destination
            items.insert(items.remove(at: index), at: destination)
        }
    }
}

Edit: There is this article by apple that I cannot believe I didn't find previously. Composing SwiftUI Gestures. I haven't experimented with it yet, but the article seems to do a great job!

like image 157
Jacob J Avatar answered Sep 29 '22 01:09

Jacob J