9

是否有任何方便的方法来确定是否从处于后台模式的应用程序加载视图?

在 3.XI 中,将依赖 viewDidLoad 进行一些初始化等,但是对于 4.X,情况并非如此,因为您不能依赖 viewDidLoad 方法被调用。

我想避免在 appdelegate 中添加额外的标志来检测这一点,我宁愿在 UIViewController 中使用可靠的方法来执行此操作,但似乎在 UIViewController 的生命周期中找不到任何可以帮助我的东西。

有任何想法吗?你如何处理这种情况?

4

3 回答 3

6

斯威夫特 5

订阅通知


       NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

        @objc func appMovedToForeground() {
            //Your code here
        }

删除通知


    override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)

            NotificationCenter.default.removeObserver(self)
    } 

于 2020-03-26T13:57:04.640 回答
3

UIViewController 的生命周期没有在将应用程序从后台移动到前台时调用的方法。

当您希望此事件触发某些特定的代码块时,您需要为名为的通知添加一个观察者Notification.Name.UIApplicationWillEnterForeground。这方面的一个例子是:

NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)

@objc func appMovedToForeground() {
    //Your code here
}

请记住,您需要删除观察者以防止它在整个应用程序中触发。

于 2018-08-09T08:04:55.840 回答
-6
- (void)viewWillAppear:(BOOL)animated

不是

- (void)viewDidLoad

应用程序委托方法

- (void)applicationWillEnterForeground:(UIApplication *)applicationUIApplicationDelegate

将在应用程序进入前台后调用,尽管您可以UIApplicationWillEnterForegroundNotification在任何视图中添加观察者。

于 2010-09-04T18:53:10.753 回答