gpt4 book ai didi

SwiftUI 从另一个 View 重新排序列表动态部分

转载 作者:行者123 更新时间:2023-12-04 15:22:38 24 4
gpt4 key购买 nike

我有一个简单的 List,其中的部分存储在 ObservableObject 中。我想从另一个 View 重新排序。

这是我的代码:

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

但是在 OrderingView 中尝试移动部分时出现此错误:“尝试为单元格创建两个动画”。可能是因为部分的顺序发生了变化。

如何更改部分的顺序?

最佳答案

这个场景的问题是多次重新创建 ViewModel,所以在 sheet 中所做的修改就丢失了。 (奇怪的是,在带有 StateObject 的 SwiftUI 2.0 中,这些更改也丢失了,EditButton 根本不起作用。)

无论如何。看起来这里是找到的解决方法。这个想法是打破面试依赖(绑定(bind))并使用纯数据将它们显式传递到工作表中并从中显式返回它们。

测试并使用 Xcode 12/iOS 14,但我尽量避免使用 SwiftUI 2.0 功能。

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(sections: viewModel.sections) {
self.viewModel.sections = $0
}
}
}

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 {
@State private var sections: [String]
let callback: ([String]) -> ()

init(sections: [String], callback: @escaping ([String]) -> ())
{
self._sections = State(initialValue: sections)
self.callback = callback
}

var body: some View {
NavigationView {
List {
ForEach(sections, id: \.self) { section in
Text(section)
}
.onMove {
self.sections.move(fromOffsets: $0, toOffset: $1)
}
}
.navigationBarItems(trailing: EditButton())
}
.onDisappear {
self.callback(self.sections)
}
}
}

关于SwiftUI 从另一个 View 重新排序列表动态部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62996572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com