按下锁定按钮的视图控制器方法?

时间:2013-08-14 21:22:13

标签: ios objective-c

当用户按下锁定按钮时,是否有可用的视图控制器方法?我正在寻找类似viewDidDisappear:viewWillDisappear:的内容,但具体针对按下锁定按钮的情况。

2 个答案:

答案 0 :(得分:2)

当用户锁定手机时,会发布名为UIApplicationDidEnterBackgroundNotification的通知。以下是如何倾听它:

在ViewController的viewDidLoad:中:

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

然后,定义一个方法(我的上面称为screenLocked)并编写您想要在屏幕被锁定时执行的代码。

-(void)screenLocked{
    //do stuff
}

此外,要进行一些必要的清理,也可以将此方法添加到ViewController中。

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

答案 1 :(得分:1)

试试这个:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  UIApplicationState state = [application applicationState];
  if (state == UIApplicationStateInactive) {
      NSLog(@"Sent to background by locking screen");
  } else if (state == UIApplicationStateBackground) {
      NSLog(@"Sent to background by home button/switching to other app");
  } 
}