Reputation: 43
I made the following minimal code reproducing my problem. If you add some entries, open one entry, dismiss the sheet by swiping down and then quickly open another entry, the first entry is displayed even though you opened another one. If you take a little more time before opening another entry, it works fine. Do you have any idea where this might be coming from? I guess I'm making mistakes in the use of SwiftData but I can't figure out where.
I know there is a similar question, this one: Wrong View Displayed When Rapidly Switching Between Sheets but it doesn't solve my problem, it makes no difference.
import SwiftUI
import SwiftData
struct ContentView: View {
@Query private var entries: [Entry]
@Environment(\.modelContext) private var context
@State private var selectedEntry: Entry?
@State private var isAdding = false
var body: some View {
NavigationView {
VStack {
List {
ForEach(entries) { entry in
Text(entry.content)
.onTapGesture {
selectedEntry = entry
}
}
}
}
.navigationTitle("Entries")
.toolbar {
ToolbarItem {
Button("Add entry", systemImage: "plus") {
isAdding = true
}
}
}
.sheet(isPresented: $isAdding) {
NavigationStack {
EntryDetail(entry: nil, in: context.container)
}
}
.sheet(item: $selectedEntry) { entry in
NavigationStack {
EntryDetail(entry: entry, in: context.container)
}
}
}
}
}
struct EntryDetail: View {
private let entry: Entry?
@State private var localEntry: Entry
private let localContext: ModelContext
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack {
Form {
TextField("Type your entry", text: $localEntry.content, axis: .vertical)
}
}
.navigationTitle("Entry")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
try? localContext.save()
dismiss()
}
}
}
}
init(entry: Entry?, in container: ModelContainer) {
localContext = ModelContext(container)
localContext.autosaveEnabled = false
if let entry {
localEntry = localContext.model(for: entry.id) as? Entry ?? Entry(content: "")
} else {
let newEntry = Entry(content: "")
localContext.insert(newEntry)
localEntry = newEntry
}
self.entry = entry
}
}
@Model
class Entry {
var content: String
init(content: String) {
self.content = content
}
}
Upvotes: 1
Views: 57