SwiftUI How to maintain scroll position in For Each loop when navigating to detail and back

Viewed 840

I'm using this NavigationButton below in order to be able to execute some code (set the selected workout) which works well but when you tap on a Row and navigate back, the scroll position in the For Each resets to the top. How can I make this view remember the scroll position so that when you navigate back you are were you left off?

// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
    var destination: () -> Destination
    var body: some View {
        self.destination()
    }
}


var body: some View {
    VStack {
        if workoutMonths.count == 0 {
            Text("No workouts logged yet.  Open the App on your Apple Watch to start and save a new workout.")
                .multilineTextAlignment(.center)
                .padding(.horizontal)
        } else {
            List {
                ForEach(workoutMonths) { workoutMonth in
                    Section(header: Text(getFormattedYearMonth(workoutMonth: workoutMonth))) {
                        ForEach(workoutMonth.trackerWorkouts) { workout in
                            NavigationButton(
                                action: {
                                    athlyticDataStore.selectedWorkout = workout //this line is needed so that the image  at the top of WorkoutDetailHeaderCard gets updated,  otherwise the view loads before the async called and you end up with the  image of the last selected workout
                                    athlyticDataStore.loadDataForSelectedWorkout(selectedWorkoutToBeUpdated: workout)
                                    generator.notificationOccurred(.success)
                                },
                                destination: {
                                    WorkoutDetailView().environmentObject(athlyticDataStore)
                                },
                                workoutRow: { WorkoutRow(trackerWorkout: workout) }
                            )
                        }
                        .onDelete { (offSets) in
                            deleteWorkout(offSets: offSets, workoutMonth: workoutMonth)
                        }
                        .buttonStyle(PlainButtonStyle()) //this removes highlight on tap of list item
                    }
                }
                
            }
        }
    }
}
0 Answers
Related