Home > other >  How to undo by code a SwiftUI swipe action on a List cell?
How to undo by code a SwiftUI swipe action on a List cell?

Time:02-05

My app has a SwiftUI List with cells that can be swiped (leading, trailing).

Problem:

Say, a cell is swiped so that the buttons are visible. Then the app is de-activated in this state, e.g. by a switch to another app, by locking the screen, etc.
When the app later is re-activated, the earlier swiped cell is still swiped, although the user might no longer be aware of the reason.
It would thus be better to undo the swipe by code, when the app is deactivated.

Question:

Is this possible?

CodePudding user response:

It is a but of a brute-force approach but redrawing with this approach works.

import SwiftUI

@available(iOS 15.0, *)
struct ResetSwipeView: View {
    @Environment(\.scenePhase) var scenePhase
    @State var id: UUID = .init()
    var body: some View {
        List(1...10){n in
            Text(n, format: .number)
                .swipeActions {
                    Button {
                        print("Button :: \(n)")
                    } label: {
                        Text("print")
                    }
                    
                }
        }.id(id)
            .onChange(of: scenePhase, perform: { newValue in
                if newValue == .inactive{
                    id = .init()
                }
            })
    }
}

@available(iOS 15.0, *)
struct ResetSwipeView_Previews: PreviewProvider {
    static var previews: some View {
        ResetSwipeView()
    }
}
  • Related