gpt4 book ai didi

swift - 如何检测从哪个 ViewController 应用程序进入后台?

转载 作者:搜寻专家 更新时间:2023-11-01 06:54:36 25 4
gpt4 key购买 nike

在我的 swift 应用程序中,我需要知道我的应用程序从哪个屏幕进入后台。我正在尝试以这种方式使用 NotificationCenter:

class MainViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundMain), name: UIApplication.didEnterBackgroundNotification, object: nil)
}

@objc func appMovedToBackgroundMain() {
print("main - App moved to Background!")
}
}

class InitViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundInit), name: UIApplication.didEnterBackgroundNotification, object: nil)
}

@objc func appMovedToBackgroundInit() {
print("init - App moved to Background!")
}
}

当我在 MainViewController 按下 Home 按钮时,我进入了 Xcode 的控制台,这些行:

init - App moved to Background!
main - App moved to Background!

我预计那里只有一行 - main - App moved to Background!。我怎样才能做到这一点?

最佳答案

在AppDelegate方法:applicationDidEnterBackgroundapplicationWillEnterForeground上,可以获得最顶层的UIViewController。在这个问题上有很好的解释:Get top most UIViewController

关于swift - 如何检测从哪个 ViewController 应用程序进入后台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com