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())
        }
    }
}
3
  • Your request doesn't make sense. Commented Jun 23, 2021 at 1:49
  • You have to add a variable to the Model that saves an index. They sort by the index Commented Jun 23, 2021 at 9:50
  • Does this answer your question? SwiftUI reorder CoreData Objects in List Commented Jun 23, 2021 at 9:52

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.