3

I have a simple List with sections that are stored inside an ObservableObject. I'd like to reorder them from another view. I have this working, and it re-orders the list sections but when you close out the app, it doesn't save the order you moved the list sections.

I want it to save the state after you re-order the sections, when I close out the app it goes back to the normal order.

class ViewModel: ObservableObject {
    @Published var sections = ["S1", "S2", "S3", "S4"]
    
    func move(from source: IndexSet, to destination: Int) {
        sections.move(fromOffsets: source, toOffset: destination)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()
    @State var showOrderingView = false

    var body: some View {
        VStack {
            Button("Reorder sections") {
                self.showOrderingView = true
            }
            list
        }
        .sheet(isPresented: $showOrderingView) {
            OrderingView(viewModel: self.viewModel)
        }
    }

    var list: some View {
        List {
            ForEach(viewModel.sections, id: \.self) { section in
                Section(header: Text(section)) {
                    ForEach(0 ..< 3, id: \.self) { _ in
                        Text("Item")
                    }
                }
            }
        }
    }
}
struct OrderingView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.sections, id: \.self) { section in
                    Text(section)
                }
                .onMove(perform: viewModel.move)
            }
            .navigationBarItems(trailing: EditButton())
        }
    }
}
GILL
  • 67
  • 6

1 Answers1

0

There are quite some options you have here. What you need in order for your app to save the states in-between sessions is data persistence.

There are several options to your disposal:

  1. Core Data Recommended option to save app data.
  2. User Defaults Older implementation and only suitable for some cases. Recommended to save for e.g. User in app settings.
  3. Databases. There are a lot of options here. Your own database, Firebase etc.
Simon
  • 1,754
  • 14
  • 32