24
votes

For an iPhone/iPad app, i have the functionality to share when someone clicks on UIBarButtonItem.

UIActivityViewController * activityVC = [[UIActivityViewController alloc] initWithActivityItems:shareItems applicationActivities:nil];

    [self presentViewController:activityVC animated:YES completion:nil];

For iPad however, this code errors because I need to set the sourceView for the activityVC.

So I need to add this code, but set it to the position of UIBarButtonItem.

activityVC.popoverPresentationController.sourceView = SomeUIBarButtonItem;

But this doesn't work since UIBarButtonItem doesn't inherit from UIView(which is really strange for me and I don't get this logic).

Is there some way to set it so that share popover appears pointing the bar button item?

Thanks,

1
Have you looked at the barButtonItem property of UIPopoverPresentationController?rmaddy
Oh, I realized there was barButtonItem, and it works as expected! Thanks for the help!Seyong Cho

1 Answers

55
votes

All you need to do is use the popover's barButtonItem property.

So a proper code to support ActivityViewController or UIAlertController on iPads:

popover.barButtonItem = self.navigationItem.rightBarButtonItem;

Another example for a full support for iPads, with UIAlertController (but works just the same with ActivityViewController):

UIPopoverPresentationController *popover = alert.popoverPresentationController;
if (popover)
{
    popover.barButtonItem = self.navigationItem.rightBarButtonItem;
    popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
}

[self presentViewController:alert animated:YES completion:nil];

Swift 4.2

if let popover = alert.popoverPresentationController {
     popover.barButtonItem  = self.navigationItem.rightBarButtonItem
     popover.permittedArrowDirections = .up
}

self.present(alert, animated: true, completion: nil)