【问题标题】:How to share data between class and view in SwiftUI如何在 SwiftUI 中的类和视图之间共享数据
【发布时间】: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
}

我的问题是我在屏幕上拖动时,板子没有变化,而且我感觉我的板子在我的不同文件中的内容不一样...

如何在视图和类之间共享数据?

谢谢。

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    我相信这是因为 @Published 更改未通过 board: [[Tile]] 数组发布。我也遇到过类似的问题,例如here。

    可以尝试为每个 Tile 对象提供对拥有它的 Board 的引用,并在需要发布更改时手动触发董事会的 objectWillChange。

    【讨论】:

      【解决方案2】:

      我会推荐以下更改(粗糙):

      1) 做一个模型,Tile,一个值类型

      struct Tile {
          var coords: Coords
          var value: Int
      }
      

      2) 让TileView 出现,听起来像Tile,并给它一个模型作为绑定(@State 供内部使用,养成给它private 的习惯)

      struct TileView: View {
         @Binding var model: Tile
         ...
      

      3) 在视图之间进行绑定

      TileView(model: self.$board.board[y][x])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多