【发布时间】:2020-02-28 22:55:53
【问题描述】:
我正在尝试构建一个 2048 游戏来学习 SwiftUI,但我被卡住了。我有三个课程,游戏,棋盘和瓷砖。 Game 有一个包含 Board 实例的变量,board 有一个包含 Tiles 矩阵的变量。
同理,我有三个视图,ContentView.swift、BoardView.swift 和 TilesView.swift
在 ContentView.swift 视图中,我像这样初始化 Game:
@ObservedObject var game = Game()
...
Blocks(board: self.game.board)
然后在 BoardView.swift 中:
@ObservedObject var board: Board
... Loop ...
TileView(value: self.board.board[y][x].value)
...
.gesture(
DragGesture()
.onChanged({ value in
let direction = self.board.gestureToDirection(startLocation: value.startLocation, location: value.location)
self.board.move(direction: direction)
})
)
在 TileView.swift 中:
@State var value: Int = 0;
Game.swift:
class Game: ObservableObject {
@Published var board = Board()
}
Board.swift:
class Board: ObservableObject {
@Published var board: [[Tile]] = []
/* Here is the logic of the game, when a gesture is triggered in ContentView.swift, I call a function to move the tiles */
}
Tiles.swift :
class Tile: ObservableObject {
@Published var coords: Coords
@Published var value: Int
}
我的问题是我在屏幕上拖动时,板子没有变化,而且我感觉我的板子在我的不同文件中的内容不一样...
如何在视图和类之间共享数据?
谢谢。
【问题讨论】: