I have a simple List in a macOS app, and on a button click I change some state and re-sort the array of items. However, it seems like it breaks cell layout in the process. Is this type of thing not allowed or preferred? Is there an alternative way to re-order items in a List?
class Model: ObservableObject {
@Published var items: [Item]
init(items: [Item]) {
self.items = items
updateQuestStatuses()
}
func updateQuestStatuses() {
items = items.sorted(by: { $0.status.rank > $1.status.rank })
}
}
struct ListView: View {
@StateObject var model: Model
var body: some View {
NavigationView {
List {
ForEach($model.items, id: \.id) { $item in
NavigationLink(destination: DetailView(item: $item, onUpdate: { [unowned model] in model.updateQuestStatuses() })) {
HStack {
Circle()
.foregroundColor(item.status.color)
.frame(width: 8, height: 8)
Text(item.title)
}
}
}
}
.frame(width: 350)
}
.background(Color(NSColor.textBackgroundColor))
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct DetailView: View {
@Binding var item: Item
let onUpdate: () -> ()
var body: some View {
Button("Change It") {
item.status = .waiting
onUpdate()
}
}
}
See project: https://github.com/UberJason/ListReorderBug