今晚我遇到了同样的问题,有几个解决方法(包括以老式方式呈现弹出框)。
对于此示例,我有一个对象存储在我的自定义单元类中。当单元格被选中时,我调用这样的函数来打开 popOverViewController 中关于对象的详细信息,并指向(锚点)它在表格中的相应单元格。
- (void)openCustomPopOverForIndexPath:(NSIndexPath *)indexPath{
CustomViewController* customView = [[self storyboard] instantiateViewControllerWithIdentifier:@"CustomViewController"];
self.myPopOver = [[UIPopoverController alloc]
initWithContentViewController:customView];
self.myPopOver.delegate = self;
//Get the cell from your table that presents the popover
MyCell *myCell = (MyCell*)[self.tableView cellForRowAtIndexPath:indexPath];
CGRect displayFrom = CGRectMake(myCell.frame.origin.x + myCell.frame.size.width, myCell.center.y + self.tableView.frame.origin.y - self.tableView.contentOffset.y, 1, 1);
[self.myPopOver presentPopoverFromRect:displayFrom
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
}
这种方法的问题是我们经常需要弹出视图有一个自定义的初始化器。如果您希望在情节提要而不是 xib 中设计视图并且有一个自定义 init 方法将您的单元格关联对象作为参数用于它的显示,那么这是有问题的。您也不能只使用 popover segue(乍一看),因为您需要一个动态锚点(并且您不能锚定到单元原型)。所以这就是我所做的:
- 首先,在您的视图控制器视图中创建一个隐藏的 1px X 1px UIButton。(重要的是要给出允许它在视图中移动的任何地方的按钮约束)
- 然后在您的视图控制器中为按钮(我称为 popOverAnchorButton)制作一个插座,并控制将一个 segue 从隐藏按钮拖动到您希望 segue 的视图控制器。让它成为一个popOver segue。
现在你有了一个带有“合法”锚的弹出框segue。该按钮是隐藏的,因此任何人都不会意外触摸它。您仅将其用于锚点。
现在只需像这样在您的函数中手动调用您的 segue。
- (void)openCustomPopOverForIndexPath:(NSIndexPath *)indexPath{
//Get the cell from your table that presents the popover
MyCell *myCell = (MyCell*)[self.tableView cellForRowAtIndexPath:indexPath];
//Make the rect you want the popover to point at.
CGRect displayFrom = CGRectMake(myCell.frame.origin.x + myCell.frame.size.width, myCell.center.y + self.tableView.frame.origin.y - self.tableView.contentOffset.y, 1, 1);
//Now move your anchor button to this location (again, make sure you made your constraints allow this)
self.popOverAnchorButton.frame = displayFrom;
[self performSegueWithIdentifier:@"CustomPopoverSegue" sender:myCell];
}
还有……瞧。现在,您正在使用 segues 的所有伟大之处的魔力,并且您拥有一个似乎指向您的单元格的动态锚点。现在-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
您可以简单地将发件人转换为您的单元格的类(假设您对发件人类型和正在调用的segue 进行了适当的检查)并将segue 的destinationViewController 提供给单元格的对象。
让我知道这是否有帮助,或者任何人有任何反馈或改进。