为什么在 iOS 中没有调用 view*Disappear 方法?

Why are the view*Disappear methods not being called in iOS?

我尝试在单击主页按钮和电源按钮时执行某些操作。我在 iOS.

开发

这是我使用的代码:

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSLog(@"viewDidDisappear");
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSLog(@"viewWillDisappear");
}

- (void)applicationFinishedRestoringState{
    NSLog(@"applicationFinishedRestoringState");
}

为什么我点击iPhone上的电源键或者home键没有调用上面的函数?

我是不是漏掉了什么?

viewDidDisappear:viewWillDisappear: 如果视图被推送或弹出,或者无论如何在您自己的运行循环中消失,将被调用,通过按主页或电源按钮进入后台不算作查看'相关事件,而是与应用程序相关的事件。您应该改为注册 UIApplicationWillResignActiveNotification 通知。

例如

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disappearSelector) name:UIApplicationWillResignActiveNotification object:nil];

根据 Apple 的文档

This method is called before the receiver’s view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call super at some point in your implementation.

要在您的应用程序恢复时收到通知,您应该使用: - (void)applicationDidBecomeActive:(UIApplication *)application这个方法在你的AppDelegate.m

中实现

另一方面

当用户锁定他们的 phone 时,会发布一个名为 UIApplicationDidEnterBackgroundNotification 的通知。收听方法如下:

viewDidLoad: 你的 ViewController:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenLocked) name:UIApplicationDidEnterBackgroundNotification object:nil];

然后在你的方法中添加一些东西

-(void)screenLocked{
    //do stuff
}