Arthur Emídio Arthur Emídio - 5 months ago 153
iOS Question

Is there a way to select a segue anchor programmatically?

Suppose I have a Storyboard containing a view that contains a button. When the user presses this button, a popover comes up.

Thus, I need to set an anchor by dragging the segue to the button using Xcode (and then do performSegueWithIdentifier:).

So, my question is: is there a way to set this "anchor" programmatically?

Thank you.

Answer

In my case I've added programmatically several UIBarButtonItem. The problem of only using an invisible view as an archor is that, if like in my case, the size of the UIBarButtonItem is changing it's size, the arrow of the popover doesnt appear centered, and althought it works, looks a bit strange.

How to solve it.

Create a small view in storyboard ( the size doesnt really matter ), make it invisible, and link it. In my case this is called invisibleViewAsArchor

Connect the UIBarbutton item with the follow action.

-(IBAction) showMyPopover:(id)sender {
    if([self.popoverController isPopoverVisible])
    {       
        [self.popoverController dismissPopoverAnimated:YES];
    }else{
        self.invisibleViewAsArchor.frame = CGRectMake([sender view].frame.origin.x,
                                                          [sender view].frame.origin.y-50,
                                                          [sender view].frame.size.width,
                                                          [sender view].frame.size.height);

        [self performSegueWithIdentifier:@"segue_to_something" sender:self];
    }
}

as you can see before it shows the popover (with performSegueWithIdentifier), I'm changing the frame of the Archor with the values from the button that has fired the event.

Hope it helps.