How to use Storyboard to make popover that can be used in code?

后端 未结 5 2041
小鲜肉
小鲜肉 2020-12-24 03:56

I\'m building a collection of forms each of which contains several fields. Some of the fields are UITextFields that will display a date. I\'ve created a new cla

5条回答
  •  余生分开走
    2020-12-24 04:27

    You can create segue that is not connected to any control but I don't think that there would be way to specify anchor point for popover from code. Another option is to create ViewController that is not connected with any segue. When editing storyboard, create ViewController which will be placed in popover, select it and navigate to Utilities pane->Attributes Inspector. Set Size to Freeform, Status Bar to None, specify unique Identifier that will be used to instantiate ViewController from code. Now you can change the size of ViewController by selecting its View and navigating to Utilities pane->Size Inspector.

    After that you can create popover from code:

    - (IBAction)buttonPressed:(id)sender {
        UIView *anchor = sender;
        UIViewController *viewControllerForPopover = 
            [self.storyboard instantiateViewControllerWithIdentifier:@"yourIdentifier"];
    
        popover = [[UIPopoverController alloc] 
                   initWithContentViewController:viewControllerForPopover];
        [popover presentPopoverFromRect:anchor.frame 
                                 inView:anchor.superview 
               permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    

    One caveat is that you need to hold reference to popover as ivar of your class, otherwise it'll crash because UIPopoverController would be released and deallocated after buttonPressed returns:

    @interface MyViewController : UIViewController {
    //  ...
        UIPopoverController *popover;
    //  ...
    }
    

提交回复
热议问题