正如 Ed Marty 已经写的那样
如果你想通过按下按钮来关闭弹出框,一些相关的地方应该保留对弹出框的引用
这是非常正确的;但是,当显示 UIPopoverController 时,打开 popovercontroller 的类已经保留了该资源。所以,你可以做的是使用这个类作为你的 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 编写代码,因此没有内存管理。
希望对你有所帮助。