【问题标题】:SWIFTUI - How to navigate to the last view after reopening the app?SWIFTUI - 重新打开应用程序后如何导航到最后一个视图?
【发布时间】:2020-12-07 06:40:14
【问题描述】:

我正在开发一个基于文本的 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?

谢谢。

【问题讨论】:

  • 您可以在 UserDefaults 中添加一个在会话之间持续存在的键,当您打开应用程序时,请检查 UserDefault 值。
  • 我使用 UserDefaults 存储变量值,但我不知道如何存储用户在哪个视图上。
  • 我会在 UserDefaults 中存储一个 String 或 Int 值,然后使用该值来确定要呈现的视图。

标签: view swiftui navigation


【解决方案1】:

在@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")
        }
        ...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多