问题
My app has one main screen that the user uses, then once they're done go to another view, currently implemented as a .fullscreencover. I want the user to be able to press a button and the app pretty much resets, turning everything back to the way it is when the app is launched for the first time and resetting all variables and classes.
The one method I have tried is opening the view again on top of the final view, however this doesn't reset it. Here is the code I have tried but doesn't work:
Button("New Game"){
newGame.toggle()
}
.fullScreenCover(isPresented: $newGame){
ContentView()
}
Alongside this I have tried navigation views however this causes more issues with the functionality of my app.
Is there a line of code that allows you to do this?
回答1:
The possible approach is to use global app state
class AppState: ObservableObject {
static let shared = AppState()
@Published var gameID = UUID()
}
and have root content view be dependent on that gameID
@main
struct SomeApp: App {
@StateObject var appState = AppState.shared // << here
var body: some Scene {
WindowGroup {
ContentView().id(appState.gameID) // << here
}
}
}
and now to reset everything to initial state from any place we just set new gameID:
Button("New Game"){
AppState.shared.gameID = UUID()
}
来源:https://stackoverflow.com/questions/65309064/reset-main-content-view-swift-ui