如何在 Xcode 中使用新的场景委托

ani*_*rud 3 xcode viewcontroller swift ios13 uiscenedelegate

我正在尝试更改标签的文本或在我的 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")
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 5

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

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

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

NotificationCenter.default.addObserver(self, selector: #selector(didActivate), name: UIScene.didActivateNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

然后添加didActivate方法:

func didActivate() {
    showMessage("Test Message")
}
Run Code Online (Sandbox Code Playgroud)

然后添加deinit

deinit {
    NotificationCenter.default.removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)

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

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