UIPopoverController和UIImagePickerControl:"无法从没有窗口的视图中呈现弹出窗口"

12

我正在尝试在我的iPad应用程序中显示UIImagePickerControl。起初,调试器告诉我,在iPad上这样做需要把它放到一个弹出窗口中。所以我编写了以下代码:

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
[popover presentPopoverFromRect:CGRectMake(0.0, 0.0, 400.0, 400.0) 
                         inView:self.view
       permittedArrowDirections:UIPopoverArrowDirectionAny 
                       animated:YES];

然而,现在我遇到了以下错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Popovers cannot be presented from a view which does not have a window.'

您有什么建议?我知道self.view应该有一个窗口,但显然... 它没有?


1
这也可能是我发现的最快速的代码块,可以快速实现弹出控制器。干得好。 - Eric Brotto
2个回答

13

如果这段代码在视图加载之前执行,那么这种情况就会发生,因为此时self.view仍然为空,因此self.view.window也为空。

你是否可能在init方法或其他在视图加载之前(在调用-viewDidLoad:之前)的地方进行此操作?


1
好的,我把函数调用移到了 -viewDidAppear: 中,现在它可以正常工作了! - Jason

2
这个错误让我感到困惑,但后来发现是因为我传递给presentPopoverFromBarButtonItembarButtonItem 是一个UIBarButtonSystemItemFlexibleSpace项目而不是一个实际的按钮。这是我的用户错误,但只是为了让大家知道,这也可能会发生。

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