Expected behaviour: When I press the button I expect the label change from "Original" to "Edited"
Obtained behaviour: This only happens in scenario A) and B) not C), the desired.
- Scenario A: action:
update2(item:)
and both labels - Scenario B: action:
update(itemID:container:)
and label:Text(item.name)
- Scenario C: action:
update(itemID:container:)
and label:ItemRow(item:)
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
Button(action: {
update(itemID: item.id, container: modelContext.container)
// update2(item: item)
},
label: {
ItemRow(item: item)
// Text(item.name)
})
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(name: "Original")
modelContext.insert(newItem)
//modelContext.save()
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
struct ItemRow: View {
let item: Item
var body: some View {
Text(item.name)
}
}
@Model
final class Item {
var name: String
init(name: String) {
self.name = name
}
}
func update(itemID: PersistentIdentifier, container: ModelContainer){
let editModelContext = ModelContext(container)
editModelContext.autosaveEnabled = false
let editModel = editModelContext.model(for: itemID) as! Item
editModel.name = "Edited"
try! editModelContext.save()
}
func update2(item: Item){
item.name = "Edited"
}