iOS SwiftUI: How to show a preview for the swipeAction on a List Row

103 Views Asked by At

I have a SwiftUI List where each row has a swipe action to add item to basket. I want to show users a preview of the swipe action so that they are aware that this action is possible. How do I go about doing this?

struct ContentView: View {
    let items = ["Item 1", "Item 2", "Item 3", "Item 4"]

    var body: some View {
        List {
            ForEach(items.indices, id: \.self) { index in
                VStack(alignment: .leading) {
                    Text(items[index])
                       .padding()
                }
                .swipeActions(edge: .leading) {
                    Button("A2B") {
                        print("added")
                    }
                    .tint(.red)
                 }
            }
        }
    }
}

I added an offset to move the row:

private struct SwipeActionAnimation: ViewModifier {
    var initialPosition: CGFloat = 0
    var finalOffset: CGFloat = 16
    var animateDuration = 0.4
    var shouldSwipe: Bool = true
    
    @State var isAnimating = false
    
    func body(content: Content) -> some View {
        content
            .onAppear {
                withAnimation(.easeInOut(duration: animateDuration)) {
                    self.isAnimating = true
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + animateDuration) {
                    withAnimation(Animation.easeInOut(duration: animateDuration)) {
                        self.isAnimating = false
                    }
                }
            }
            .offset(x: isAnimating ? finalOffset : initialPosition)
    }

This would be added as a modifier to the row:

VStack(alignment: .leading) {
...
}
.modifier(SwipeActionAnimation())

But this does not show the swipeActionButton. Just offsets the row and brings it back. I want to show the preview for the swipeActionButton "Add to Basket" during this animation.

0

There are 0 best solutions below