@Published变量上的@Binding发生更改-但除非我走出并返回屏幕,否则不会更新视图

时间:2019-12-30 08:24:27

标签: swift swiftui

在SwiftUI中,我在一个Observable对象中有一个@Published变量:

class MasterKey: ObservableObject{
    @Published var keycode : Int = 0
    @Published var current_index : Int = 0
    @Published var game_length : Int = 1
}

通过@Binding变量进入视图:

class AppDelegate: NSObject, NSApplicationDelegate {

    @ObservedObject var masterkey = MasterKey()
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let contentView = ContentView(keycode:self.$masterkey.keycode,
                                      current_index:self.$masterkey.current_index,
                                      game_length:self.$masterkey.game_length)
    ....
}

struct ContentView: View {


    @State var board_history : [[[String]]] = [default_board]

    @Binding var keycode : Int
    @Binding var current_index : Int
    @Binding var game_length: Int

    ...
    Piece(name:self.board_history[self.current_index][x][y],
                                  released: self.released,
                                  index_x: x,
                                  index_y: y)
}

当我通过不同的视图更新current_index时,似乎变量已更新,但ContentView不会自动刷新,即使它是已发布的变量也是如此。仍然很奇怪,当我切换应用程序并返回时(例如,我将应用程序最小化,然后重新打开),ContentView会更新为应有的状态。为什么会这样呢?我认为,当@Published变量更改时,所有依赖于它们的视图都将自动更新。

1 个答案:

答案 0 :(得分:0)

@ObservedObject应该在SwiftUI视图中使用,因此您的代码应类似于以下内容...

class AppDelegate: NSObject, NSApplicationDelegate {

    var masterkey = MasterKey()
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let contentView = ContentView(model: masterkey)

然后

struct ContentView: View {

    @ObservedObject var model: MasterKey
    @State private var board_history : [[[String]]] = [default_board]

    ...
    Piece(name:self.board_history[self.model.current_index][x][y],