SWIFTUI-如何在重新打开应用程序后导航到最后一个视图



我正在开发一款基于文本的rpg游戏。将会有大量的视图;在每个决策之后,用户将导航到一个新的视图。但如果用户关闭应用程序并重新打开它,他们将失去所有进度,从主视图开始。

有没有一种方法可以创建一个";继续";按钮将用户带到他们上次访问的视图?或者,当他们重新打开应用程序时,有没有办法直接打开最后一个视图?

例如,用户将从以下内容开始:

struct ContentView: View {
var body: some View {
NavigationLink(destination: View1()) {
Text(Start)
}
}
}

在播放了一段时间后,用户在View28 上

struct View28: View {
var body: some View {
NavigationLink(destination: View29()) {
Text(Do This)
}
NavigationLink(destination: View30()) {
Text(Do That)
}
}
}

用户关闭游戏,重新打开它,然后他/她再次出现在ContentView上。

struct ContentView: View {
var body: some View {
NavigationLink(destination: View1()) {
Text(To View1)
}
NavigationLink(destination: LastViewedView()) {
Text(Continue)
}
}
}

有没有一种方法可以添加一个";继续";按钮将用户带到View28?

或者有没有一种方法可以对应用程序进行编程,直接重新打开View28?

谢谢。

在@nicksarno的建议下,我想我找到了一种解决问题的原始方法。

我创建了一个全局变量

var ViewCounter = 0

每次查看后,我都添加了以下代码:

// ViewCounter will take the value of which view it is on, and UserDefaults will save the value.
.onAppear() {  
ViewCounter = 28
UserDefaults.standard.set(ViewCounter, forKey: "Save1")
}

在ContentView中,首先检索ViewCounter:的值

onAppear() {
guard let retrievedmsg1 = UserDefaults.standard.value(forKey: "Save1") else {return}
ViewCounter = retrievedmsg1 as! Int
}

然后,我创建了一个状态变量,并创建一个函数来匹配ViewCounter:

@State var SelfViewCounter = 0
func ViewCountCheck() {

SelfViewCounter = ViewCounter
}

在onAppear下,我调用了函数:

self.ViewCountCheck()

最后,我创建了一个开始按钮和一个导航按钮条件:

// This is to start the game
NavigationLink(destination: View1()) {
Text("Start")
}
if SelfViewCounter == 1 {
NavigationLink(destination: View1()) {
Text("Continue")
}
} else if SelfViewCounter == 2 {
NavigationLink(destination: View2()) {
Text("Continue")
}
...

我知道它需要大量的硬编码,并且需要大量的时间来实现。但它是有效的。我很确定需要比这更好的方法,所以请补充。谢谢。

相关内容

最新更新