Is there a way to select a segue anchor programmatically?

北城以北 提交于 2020-01-01 01:53:12

问题


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.


回答1:


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.




回答2:


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>



回答3:


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!




回答4:


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.



来源:https://stackoverflow.com/questions/9450664/is-there-a-way-to-select-a-segue-anchor-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!