当应用程序进入后台时,关闭modalviewcontroller

时间:2011-04-16 08:51:59

标签: iphone background modalviewcontroller

我需要在应用程序进入后台时自动解除我的uiimagepicker模态视图控制器。我试图将代码放入viewdiddissappear方法中的dismissmodalviewcontroller代码,但它没有被调用。所以我在appdelegate中引用了viewcontroller并试过将它放在applicationdidenterbackground方法中,但它仍然没有工作。有人指出正确的方法来做到这一点

3 个答案:

答案 0 :(得分:7)

尝试在要关闭的UIViewController中为UIApplicationDidEnterBackgroundNotification添加NSNotificationCenter观察器。使用选择器关闭模态视图

- (void)viewWillAppear:(BOOL)animated
{
   [[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(didEnterBackground:) 
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];
}

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

- (void)didEnterBackground:(NSNotification*)note
{
  [self.navigationController dismissModalViewAnimated:NO];
}

答案 1 :(得分:2)

当应用移动到后台时移除模态的最佳方法,它可以正常工作。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

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

- (void)dismissView:(id)sender {
     [self dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {

     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

你也可以删除像这样的观察者

 [[NSNotificationCenter defaultCenter] removeObserver: self
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

答案 2 :(得分:1)

我认为你不需要经历所有这些。

来自the docs

If you present several modal view controllers in succession, and thus build a stack of modal view controllers, calling this method on a view controller lower in the stack dismisses its immediate child view controller and all view controllers above that child on the stack.

尝试在[self dismissModalViewController:NO]的实施中从父视图控制器调用- (void) viewDidUnload

这是未经测试的,但文档暗示它应该为您完成这项工作。