簡體   English   中英

SWIFTUI - 重新打開應用程序后如何導航到最后一個視圖?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM