【问题标题】:Re-Ordering List Sections SwiftUI重新排序列表部分 SwiftUI
【发布时间】: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())
        }
    }
}

【问题讨论】:

标签: ios swift swiftui


【解决方案1】:

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

您有多种选择:

  1. Core Data 保存应用数据的推荐选项。
  2. User Defaults 较旧的实现,仅适用于某些情况。建议保存例如应用设置中的用户。
  3. 数据库。这里有很多选择。您自己的数据库、Firebase 等。

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多