我是 Swift 編程的新手,并且整理了一些教程來嘗試制作一個簡單的 Minesweeper iOS 應用程式。我想在底部有一個選單,其中包含重置板的選項。我在 Game.swift 中有一個重置棋盤的函式,主導航在 MinesweeperApp.swift 中。我無法弄清楚如何從導航呼叫重置功能而不會出錯。
我的專案結構是這樣的:
Minesweeper
├ View
| ├ CellView.swift
| └ BoardView.swift
├ Model
| ├ GameSettings.swift
| ├ Game.swift
| ├ Cell.swift
| └ Cell Swift.swift
├ Shared
| ├ Assets.xcassets
| ├ MinesweeperApp.swift
| └ ContentView.swift
我的 Game.swift 檔案:
class Game: ObservableObject {
// the game settings
@Published var settings: GameSettings
@Published var board: [[Cell]]
init(from settings: GameSettings) {
self.settings = settings
self.board = Game.GenerateBoard(from: settings)
}
... etc ...
func resetBoard() {
self.board = Game.GenerateBoard(from: settings)
}
我的 MinesweeperApp.swift 檔案:
@main
struct MinesweeperApp: App {
var gameSettings = GameSettings() // the game settings
var body: some Scene {
WindowGroup {
NavigationView {
BoardView() // our content view
.environmentObject(Game(from: gameSettings)).padding()
.navigationTitle("Minesweeper")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button("Reset") {
Game.resetBoard()
print("Pressed")
}
}
}
}
}
}
}
當我在 MinesweeperApp 中取出 Game.resetBoard() 行時,它可以正常作業并列印“按下”。當我添加該行時,我得到的錯誤說
Instance member 'resetBoard' cannot be used on type 'Game'; did you mean to use a value of this type instead?
所以,我試圖弄清楚如何/在哪里正確呼叫重置函式。
我使用的教程是
- 掃雷:https : //levelup.gitconnected.com/swiftui-minesweeper-cd145f888343
- 添加導航選單:https : //www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-toolbar-and-add-buttons-to-it
uj5u.com熱心網友回復:
現在,因為你創建的實體Game 中的environmentObject呼叫,您不必存盤在基準App操縱水平。
最簡單的解決方法是:
@main
struct MinesweeperApp: App {
var game = Game(from: GameSettings())
var body: some Scene {
WindowGroup {
NavigationView {
BoardView() // our content view
.environmentObject(game)
.padding()
.navigationTitle("Minesweeper")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button("Reset") {
game.resetBoard() //<-- Here
print("Pressed")
}
}
}
}
}
}
}
然后,你可以呼叫resetBoard的情況下的Game,而不是試圖把它的型別(這就是為什么你得到錯誤現在)。
當然,這將取決于您的子視圖(如Board)使用@EnvironmentObject var game : Game而不是@EnvironmentObject var gameSettings : GameSettings. 而且,您可以通過以下方式訪問子視圖中的設定game.settings
uj5u.com熱心網友回復:
Game = 不能呼叫非靜態函式的類游戲。您需要在使用“.resetBoard()”之前創建物件,我認為它將在您的 MinesweeperApp 之上。
struct MinesweeperApp: App {
var gameSettings = GameSettings() // the game settings
//...
var game = Game(from settings: gameSettings)
var body: some Scene {
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407084.html
標籤:
