[英]Classes gets initialized every time on navigation back and forward swiftUI
我有這個 navigationStack,它有許多指向游戲菜單的 NavigationLinks,用戶可以在其中選擇要玩的游戲。 此菜單還包含導航鏈接,這些鏈接會導致特定類型的游戲。 游戲菜單如下所示:
struct GameMenuView: View {
@Environment(\.presentationMode) var mode: Binding<PresentationMode>
var body: some View {
VStack{
ButtonGame(game_name: "Title", view: AnyView(GameScreen(game: NewGame(count: 4, category: "All"))))
ButtonGame(game_name: "Title", view: AnyView(GameScreen(game: NewGame(count: 6, category: "2"))))
ButtonGame(game_name: "Title", view: AnyView(GameScreen(game: NewGame(count: 4, category: "None"))))
ButtonGame(game_name: "Title", view: AnyView(GameScreen(game: NewGame(count: 4, category: "Basic"))))
}
}
}
ButtonGame 只是一個結構,它接受 NavigationLink 應該導致的視圖。 游戲屏幕的視圖采用 NewGame class,它處理所有游戲邏輯和統計數據。 這一切都很好,但我發現每次從主菜單導航到游戲菜單時,所有這 4 個 NewGame 類都會被初始化,而且當從 GameMenu 導航到實際的 GameView 時,所有 NewGame 類都會再次初始化。 當我從游戲視圖導航回游戲菜單視圖時,也會發生同樣的事情。
這會導致不必要的數據加載,並且還會導致游戲在您每次離開游戲視圖時丟失其 state。 如何最好地處理這個問題? 這樣特定的游戲只有在按下該游戲的按鈕時才會被初始化,並且當導航回游戲菜單時不會導致所有內容再次重新加載?
在 Swift(和 SwiftUI)中,我們對 model 數據使用結構而不是類。 數據總是事先准備好,存儲在@State
中,然后body
使用數據創建視圖。 所以只需將Game
更改為這樣的結構:
struct Game: Identifiable {
let id = UUID()
let count: Int
let category: String
}
struct GameMenuView: View {
@Environment(\.presentationMode) var mode: Binding<PresentationMode>
@State var games = [Game(count: 4, category: "All"), Game(count: 6, category: "2"), Game(count: 4, category: "None"), Game(count: 4, category: "Basic")]
var body: some View {
List {
ForEach($games) { $game in
ButtonGame(gameName: "Title", game: $game)
}
}
}
}
struct ButtonGame: View {
@Binding var game: Game
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.