Is there a way to select a segue anchor programmatically?

前端 未结 4 1989
有刺的猬
有刺的猬 2021-02-07 09:54

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 th

相关标签:
4条回答
  • 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.

    0 讨论(0)
  • 2021-02-07 10:25

    In the storyboard anchor the popover to some arbitrary button. Don't worry too much about which one as it will get overridden in the code.

    In the view controller method prepareForSegue, add the code:

    let dest = segue.destinationViewController
    dest.popoverPresentationController?.barButtonItem = <your bar button here>
    

    or if you want to anchor to a view instead

    dest.popoverPresentationController?.barButtonItem = nil
    dest.popoverPresentationController?.sourceView = <your view here>
    
    0 讨论(0)
  • 2021-02-07 10:28

    I had the same problem where I was creating a BarButtonItem programmatically. You may also be able to get around it by creating an invisible, disabled button which you can set as the anchor in IB.

    0 讨论(0)
  • 2021-02-07 10:52

    You can't programmatically create segue's as explained here: Creating a segue programmatically, however, you can configure which destination controller you want to display at run-time. This is explained in the apple documentation here: Configuring the Destination Controller When a Segue is Triggered.

    Hopefully this helps!

    0 讨论(0)
提交回复
热议问题