我有一个可以更新领域对象的视图,当我这样做时,视图会关闭,这是不需要的行为,在对象更新后,视图应该仍然在屏幕上。这里可能存在什么问题以及可能的解决方案?
struct CardView: View {
@ObservedRealmObject var card: Card
@State private var frontText: String = ""
@State private var backText: String = ""
@EnvironmentObject private var realmManager: RealmManager
var body: some View {
VStack {
TextField("", text: $frontText)
Divider()
TextField("", text: $backText)
}
.onAppear {
frontText = card.front
backText = card.back
}
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button {
do {
try realmManager.realm?.write {
guard let card = card.thaw() else { return }
card.front = frontText
card.back = backText
}
} catch {
print(error.localizedDescription)
}
} label: {
Text("Update")
}
}
}
}
}
视图如何打开:
List {
ForEach(deck.cards) { card in
NavigationLink {
CardView(card: card)
.environmentObject(RealmManager())
} label: {
Text(card.front)
}
}
}
我找到了解决办法:
NavigationView {
// ...
}
.navigationViewStyle(.stack)
我在 NavigationView 上使用了这个修饰符,它成功了。