正如Ed Marty所写
如果您想通过按按钮来关闭弹出窗口,某个相关的地方应该保留对弹出窗口的引用
这是非常正确的;然而,在显示UIPopoverController时,打开popovercontroller的类已经保留了这个资源。因此,您可以将此类用作Popover Controller的委托类。
为此,您可以执行以下操作,我在我的代码中使用:
在打开popover的类中,这是我的代码:
- (void)showInformationForView:(Booking*)booking frame:(CGRect)rect
{
BookingDetailsViewController *bookingView = [[BookingDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped booking:booking];
[bookingView setDelegate:self];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:bookingView];
self.popController = [[UIPopoverController alloc] initWithContentViewController:navController];
[self.popController setDelegate:self];
[self.popController setPopoverContentSize:CGSizeMake(320, 320)];
rect.size.width = 0;
[self.popController presentPopoverFromRect:rect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
}
- (void)dismissPopoverAnimated:(BOOL)animated
{
[self.popController dismissPopoverAnimated:animated];
}
所以我在这里做的是创建一个
UINavigationController
,并将
BookingDetailsViewController
设置为其
rootViewController
。然后我还将当前类添加为此
BookingDetailsViewController
的代理。
我添加的第二件事是一个名为
dismissPopoverAnimated:animated
的解散方法。
在我的
BookingDetailsViewController.h
中,我添加了以下代码:
[...]
@property (nonatomic, strong) id delegate
[...]
在我的BookingDetailsViewController.m
中,我添加了以下代码:
[...]
@synthesize delegate = _delegate;
- (void)viewDidLoad
{
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(closeView)];
[self.navigationItem setRightBarButtonItem:closeButton];
[super viewDidLoad];
}
- (void)closeView
{
if ([self.delegate respondsToSelector:@selector(dismissPopoverAnimated:)]) {
[self.delegate dismissPopoverAnimated:YES];
}
else {
NSLog(@"Cannot close the view, nu such dismiss method");
}
}
[...]
发生的情况是当 UINavigationController 中的“关闭”按钮被按下时,会调用方法
closeView
。该方法检查代理是否响应
dismissPopoverAnimated:animated
,如果是,则调用它。如果不响应此方法,则会显示日志消息并什么也不做(因此不会崩溃)。
我使用 ARC 编写了我的代码,因此没有内存管理。
希望这可以帮助你。