SwiftUI: ListItem gestures

后端 未结 2 722
离开以前
离开以前 2021-02-04 14:05

Target is a modification with the following behavior:

(but only with 2 buttons - 1 on the left side, 1 on the right)

Behavior:

  • short swipe

2条回答
  •  北海茫月
    2021-02-04 14:38

    "How to implement swipe to delete?"

    As long as you don't want to create custom UI for the delete button, you can take advantage of SwiftUI and use all of the built in features.

    ForEach has a modifier called .onDelete, that gives you an IndexSet. This represents the rows that should be deleted when the user swipes. Now if we implement the necessary logic and wrap it in an animation block, everything will work as needed.

    struct ContentView: View {
        @State var cars = ["Tesla Model 3", "BMW i3", "Roadster", "Cybertruck", "Agera Koenigsegg", "Rimac Concept One"]
    
        var body: some View {
            NavigationView {
                List {
                    ForEach(cars, id: \.self) { car in
                        Text(car)
                    }
                    .onDelete { indexSet in
                        withAnimation {
                            cars.remove(atOffsets: indexSet)
                        }
                    }
                }
                .navigationTitle("My Cars")
            }
        }
    }
    

    Note: .onDelete modifier is not available to use with List, can only be applied on ForEach.

    "How to make a 2 fingers swipe gesture in SwiftUI?"

    As of now SwiftUI does not have support for creating gestures for multiple fingers. The only solution is to use UIViewRepresentable in combination with UIPanGestureRecognizer. Then you can set the minimumNumberOfTouches to 2 fingers.

    This post from Apple Developer Forum shows how you could achieve something similar for a simple 2 fingers tap gesture, but the idea and concept for swipe are very similar and already explained above.

    Hope this helps!

提交回复
热议问题