如何关闭应用程序在ios上输入背景时的模式视图

问题描述:

我有一个在方法中创建的模式视图(在mainview中没有引用),我想在应用程序在后台输入时自动执行dismissModalViewControllerAnimated。我怎样才能做到这一点 ?如何关闭应用程序在ios上输入背景时的模式视图

在mainview的viewDidLoad中,添加观察者以在应用转到背景时收到通知。

- (void) viewDidLoad 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
     selector:@selector(goToBackground) 
     name:UIApplicationWillResignActiveNotification object:nil]; 
} 

定义函数goToBackground()。当应用程序被切换到后台它将被称为

- (void) goToBackground 
{ 
    [self dismissModalViewControllerAnimated: NO]; // no need to animate 
} 

不要忘记删除观察者

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

您可以使用通知。从ApplicationDelegate的方法applicationDidEnterBackground发布通知:. YOu可以从模态控制器调用解除方法,因此将其作为观察者添加到通知中心。