我有一个简单的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())
}
}
}
但在OrderingView
当尝试移动部分时,我收到此错误:“尝试为单元格创建两个动画”。可能是因为各部分的顺序发生了变化。
如何更改各部分的顺序?
此场景的问题已重现多次ViewModel
,因此在工作表中所做的修改就丢失了。 (奇怪的是,在带有 StateObject 的 SwiftUI 2.0 中,这些更改也丢失了,并且 EditButton 根本不起作用。)
反正。看起来这是一个找到的解决方法。这个想法是打破面试依赖性(绑定)并使用纯数据将它们显式传递到工作表中并从其中显式返回它们。
使用 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)
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)