重新排序列表部分SwiftUI



我有一个简单的List,其中包含存储在ObservableObject中的部分。我想从另一个角度重新排序。我有这个功能,它会重新排序列表部分,但当你关闭应用程序时,它不会保存你移动列表部分的顺序。

我希望它在你重新订购部分后保存状态,当我关闭应用程序时,它会恢复到正常顺序。

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())
}
}
}

这里有很多选项。为了让你的应用程序在会话之间保存状态,你需要的是数据持久性。

有几个选项可供您选择:

  1. 核心数据推荐选项,用于保存应用程序数据
  2. 用户默认值较旧的实现,仅适用于某些情况。建议保存,例如用户应用内设置
  3. 数据库。这里有很多选择。您自己的数据库、Firebase等

最新更新