I have two views - a MasterView and DetailView. When opening the DetailView, I initialise a new class that tracks data about the view (in the real implementation, the detail view involves a game).
However, when I press the back button from the DetailView to return to the MasterView, and then press the button to return to the DetailView, my class is unchanged. However, I would like to re-initialise a new copy of this class (in my case to re-start the game) whenever I move from the MasterView to the DetailView.
I have condensed the problem to this code:
import SwiftUI
import Combine
class Model: ObservableObject {
@Published var mytext: String = "mytext"
}
struct MasterView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView(model: Model())) {
Text("press me")
}
}
}
}
struct DetailView: View {
@ObservedObject var model: Model = Model()
var body: some View {
TextField("Enter here", text: $model.mytext)
}
}
struct MasterView_Previews: PreviewProvider {
static var previews: some View {
MasterView()
}
}
I would like to create a new instance of Model every time I click the NavigationLink to the detail view, but it seems like it always refers back to the same original instance - I can see this by typing a change into the text field of the DetailView, which persists if I go back and forward again.
Is there any way of doing this?
DetailView(model: Model()in what you are passing toDetailView. If you are using SwiftUI, why are you not creating anEnvironmentObject? (You don't need to, but it makes it much easier.) It's theModel()- particularly the()piece - that looks to me like it screwing you. That's the "create a "new instance" or "refer to the same original instance" you are referring to. Creating one instance of your model and use that throughout. - user7014451DetailView(Model(settings=a))andDetailView(Model(settings=b))- mxt533Model == AppState, what am I missing? Stated another way (and using UIKit instead of SwiftUI, but it really doesn't matter), let's say you have three view controllers - A, B, and C. All all embedded in a UINavigationController. VC "A" has a button saying "press me" and when done, VC "B" displays a text field, which is passed to be used by VC "C". Is this pretty much what you want? If so, why do you need more than one instance of everything? I'm sure I'm missing something. - user7014451MasterViewis the main menu from which you can tap on a difficulty level (each presented byDetailView).Modelstores a single game's variables, including difficulty level (this is what I meant bysettings=aetc), high score, and gameIsOver. That's why, back in the main menu, clicking on a game again, I want it to restart, and I thought I would achieve this by passing a new instance ofModel. Does this make more sense? - mxt533