我正在制作一個簡單的掃雷應用程式。在底部我有一個帶有按鈕的工具列,用于切換游戲是否處于“標記模式”。我有兩個可能的按鈕本身的影像 - 一個用于啟用標記模式時,另一個用于未啟用時 - 我希望它在單擊時在兩者之間切換。
本質上,我想使用自定義影像進行切換以進行開/關。
但是,我下面的代碼沒有更新影像,我不知道為什么。
GameView() // the content view
.environmentObject(game)
.padding()
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Button(action: game.toggleFlagMode) {
if game.isFlagMode {
Image("flag toggle on")
.resizable()
.aspectRatio(contentMode: .fit)
}
else {
Image("flag toggle off")
.resizable()
.aspectRatio(contentMode: .fit)
}
}
Button("Reset") {
game.resetBoard()
}
}
}
還有我的 Game.swift 檔案(縮短為相關內容)
import Foundation
class Game: ObservableObject {
@Published var isFlagMode: Bool
[ ... ]
init(from settings: GameSettings) {
self.isFlagMode = false
[ ... ]
}
// toggle whether the game is in mode to flag cells
func toggleFlagMode() {
self.isFlagMode = !self.isFlagMode
}
標志模式正在通過按鈕正確切換。那就是-當我單擊它以啟用它在單擊時正確標記單元格時。所以我認為問題在于視圖而不是游戲本身。
編輯(解決方案):
我的主要 MinesweeperApp.swift 檔案中有這段代碼。我將工具列代碼放入 MinesweeperApp 呼叫的另一個視圖中,它開始作業。
uj5u.com熱心網友回復:
你有幾個錯誤:
在 viewModel 中,您可以:
func toggleFlagMode() {
self.isFlagMode.toggle()
}
在視圖中:
.environmentObject(game)
.padding()
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Button(action: game.toggleFlagMode) {
Image(systemName: game.isFlagMode ? "square.and.arrow.up" : "pencil")
.resizable()
.aspectRatio(contentMode: .fit)
.foregroundColor(.red)
}
Button("Reset") {
game.resetBoard()
}
}
}
如果您使用匯入的影像(來自資產),請記住洗掉系統名稱。

uj5u.com熱心網友回復:
處理此問題的最簡單方法是使用 @State 變數。換句話說,它是一個在狀態改變時更新視圖的變數。例如。
@State var isFlaggingModeEnabled = false
var body: some View {
Button(action: { isFlaggingModeEnabled.toggle() },
label: {
switch isFlaggingModeEnabled {
case true:
// Your image for when enabled.
default:
// Your image for when disabled.
}
}
}
uj5u.com熱心網友回復:
GameView() // the content view
.environmentObject(game)
.padding()
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Button(action: {
game.toggleFlagMode()
}) {
Image(game.isFlagMode ? "poire" : "pomme")
.resizable()
.aspectRatio(contentMode: .fit)
}
Button("Reset") {
game.resetBoard()
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416284.html
標籤:
