First, you should create a popover segue from your view controller with your table view in it. You can do this by control dragging from the yellow view controller icon in the document outline to the view controller you want to popover. Give it a segue identifier, by clicking on the segue and opening the attributes inspector and adding it to the segue identifier field. Something like "Popover" will work for now.
Next, you should drag from the anchor view circle below the segue identifier field to your view controller's view (we'll adjust this later in code).
You should add a button to your UITableViewCell
subclass. Then in your cellForRowAtIndexPath:
you can add a target for the button like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [menuItems objectAtIndex:indexPath.row]; // I'm not sure what's going on here but hopefully you do
RegisterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.PopoverAnchorButton addTarget:self action:@selector(presentPopover:) forControlEvents:UIControlEventTouchUpInside];
// Configure the cell...
return cell;
}
Add the presentPopover:
method to your view controller:
- (void) presentPopover:(UIButton *)sender
{
[self performSegueWithIdentifier:@"Popover" sender:sender];
}
Now, you can change the source view in your view controller's prepareForSegue:
You can get a reference to the UIPopoverPresentationController
and check if the source view is an instance of your subclass of UITableViewCell
. If so, adjust the source view to its button.
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Popover"] && segue.destinationViewController.popoverPresentationController) {
UIPopoverPresentationController *popController = segue.destinationViewController.popoverPresentationController;
popController.sourceView = sender;
popController.delegate = self;
// if you need to pass data you can access the index path for the cell the button was pressed by saying the following
CGPoint location = [self.tableView convertPoint:sender.bounds.origin fromView:sender];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
// do something with the indexPath
}
}
If you want the view controller to always be displayed as a popover even on implement the UIPopoverPresentationControllerDelegate
method:
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller{
return UIModalPresentationStyleNone;
}
At this point, you'll likely have a warning. This can by silenced by telling the complier that you conform to the UIPopoverPresentationControllerDelegate
protocol. For example:
@interface MyTableViewController () <UITableViewDataSource, UITableViewDelegate,UIPopoverPresentationControllerDelegate>