如何在iOS应用程序进入后台时关闭模态视图

3

我有一个模态视图是在一个方法中创建的(主视图中没有引用),我想要在我的应用进入后台时自动执行dismissModalViewControllerAnimated。我该怎么做?

2个回答

9
在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];
}

1

您可以使用通知。从ApplicationDelegate的方法applicationDidEnterBackground:发布通知。您可以将模态控制器添加为通知中心的观察者,以便从中调用dismiss方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接