从场景委托在视图控制器中更新变量的最佳方法是什么?

时间:2020-06-02 14:25:35

标签: swift

我正在使用Spotify SDK。当用户更改播放器状态时,我想在某些视图控制器中更改标签。这是我的场景代表:

var playerViewController = MatchViewController()

func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
    playerViewController.stateChanged(playerState)
}

视图控制器:

func stateChanged(_ playerState: SPTAppRemotePlayerState) {
    // aLabel.text = playerState.track.name
}

问题是状态更改时标签或其他插座为零,因为此时未加载视图控制器。我该如何解决? (我尝试过isViewLoaded)

1 个答案:

答案 0 :(得分:1)

如果要根据一个地方发生的更改来更新多个地方,请使用观察者。这样,

像这样在SceneDelegate中发布通知:

for (int i = 0; i < 4; i++) {
    if (Menschen[i] instanceof Student) {
        System.out.println("Name: " + Menschen[i].getName() + ", Geschlecht" 
                           + Menschen[i].getGeschlecht() + ", Matrikelnummer: " 
                           + ", Typ: " + Menschen[i].getTyp());
    } else {
        System.out.println("Name; " + Menschen[i].getName() + ", Geschlecht" 
                       + Menschen[i].getGeschlecht()+", Typ: "+Menschen[i].getTyp() + ".");
    }
}

像这样在ViewController中观察

func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "stateChanged"), object: nil, userInfo: ["playerState": playerState])
}