![](/img/trans.png)
[英]Forcing App to Navigate to a specific view within AppDidBecomeActive
[英]SWIFTUI - How to navigate to the last view after reopening the app?
我正在开发一个基于文本的 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
}
然后我创建了一个 state 变量并创建了一个 function 以将其与 ViewCounter 匹配:
@State var SelfViewCounter = 0
func ViewCountCheck() {
SelfViewCounter = ViewCounter
}
在 onAppear 下,我调用了 function:
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")
}
...
我知道它需要大量的硬编码并且需要很多时间来实现。 但它有效。 我很确定需要比这更好的方法,所以请补充。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.