Reset main content view - Swift UI

霸气de小男生 提交于 2021-02-10 18:20:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!