2

当我的 iOS 应用程序从后台状态变为活动状态时,我正在尝试更改标签的文本或显示警报。

当我在 ViewController 类中调用一个函数时,只有 print() 方法可以正常工作。但是当我想与该类中的对象交互时,它会显示错误。

SceneDelegate.swift:

var vc = ViewController()

func sceneDidBecomeActive(_ scene: UIScene) {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.

    vc.showMessage("Test message")
}

ViewController.swift:

@IBOutlet weak var textLabel: UILabel!

func showMessage(_ incomingMessage:String!) {
    let warning = UIAlertController(title: "Warning", message: incomingMessage, preferredStyle: .alert)
    let aButton = UIAlertAction(title: "OK", style: .cancel, handler: nil)
    warning.addAction(aButton)

    self.present(warning, animated: true)

    textLabel.text = incomingMessage

    print("message is : " + incomingMessage)
}
4

1 回答 1

5

与往常一样,正确的解决方案是让视图控制器监听相应的生命周期事件,而不是让应用程序委托或场景委托尝试告诉视图控制器任何事情。

在您的场景委托中,删除创建ViewController和尝试调用showMessage.

然后更新你的ViewController班级。将以下内容添加到viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(didActivate), name: UIScene.didActivateNotification, object: nil)

然后添加didActivate方法:

func didActivate() {
    showMessage("Test Message")
}

然后添加deinit

deinit {
    NotificationCenter.default.removeObserver(self)
}

这样,只有视图控制器需要知道它需要做什么以及什么时候做的逻辑。

另请注意,如果您真的想检测场景何时从后台返回(进入前台),请使用willEnterForegroundNotification通知而不是didActivateNotification.

于 2019-10-24T14:58:23.890 回答