【发布时间】:2021-06-23 01:46:59
【问题描述】:
我有一个简单的列表,其中包含存储在 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())
}
}
}
【问题讨论】:
-
您的请求没有意义。
-
您必须向保存索引的模型添加一个变量。他们按索引排序
-
这能回答你的问题吗? SwiftUI reorder CoreData Objects in List