creating button for popover view anchor at run time creating button for popover view anchor at run time ios ios

creating button for popover view anchor at run time


I had the same problem and solved it by creating a UIBarButtonItem in the Storyboard for the view controller but not part of the view hierarchy.

In IB, Drag a bar button item to the dark bar below the view controller view, drop it next to the "First Responder" and "View Controller" icons. Create a (strong) IBOutlet for it. Then create a popover segue from it to the destination view controller by dragging from the bar button item to the destination. It seems like this is the only way to set it as the anchor. Choosing it as the anchor for an existing segue does not work (looks like an IB bug).

enter image description here

In viewDidLoad you can assign this bar button item to the navigationItem (or where ever you like) and the segue works as expected.


I was curious about this too so I made a quick test project. You're right, there doesn't seem to be a way to configure the popover segue at runtime or add an anchor point to a button that's not in the view hierarchy using Interface Builder.

My solution was to set everything up in IB with the UIBarButtonItem visible and connected to an IBOutlet property, then remove it from the navigation bar in -viewDidLoad:

- (void)viewDidLoad{    [super viewDidLoad];    self.navigationItem.rightBarButtonItem = nil;}

Then I simply add it back or remove it by tapping another button:

- (IBAction)toggleBarButtonItem:(id)sender{    UIBarButtonItem *item = (self.navigationItem.rightBarButtonItem == nil) ?  self.popoverBarButtonItem : nil;    [self.navigationItem setRightBarButtonItem:item animated:YES];}

You could conditionally keep or remove the button in -viewDidLoad the same way. The segue remains anchored to the UIBarButtonItem.


I'm gonna try making a dummy view that's the size and shape of the views I want to present the popover from, wire that to the segue popover target, and then move the view to the right position in prepareForSegue:sender: