QCD_IS_GOOD
QCD_IS_GOOD

Reputation: 465

@Binding on a @Published variable changes - but does not update view unless I go out and come back to screen

In SwiftUI, I have a @Published variable in an Observable Object:

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

Fed into a view through @Binding variables:

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)
}

When I update current_index through a different view, it seems the variable gets updated but ContentView doesn't automatically refresh, even though it is a published variable. Weirder still, when I switch apps and come back (say that I minimise the app, then reopen it), the ContentView updates to what it should be. Why is this happening? I thought that when @Published variables changed, any views that depended on them would automatically update.

Upvotes: 1

Views: 1224

Answers (1)

Asperi
Asperi

Reputation: 257493

@ObservedObject should be used inside SwiftUI view, so your code should rather look like the following...

class AppDelegate: NSObject, NSApplicationDelegate {

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

then in

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],

Upvotes: 1

Related Questions