How to make UIPopoverController keep same position after rotating?

前端 未结 13 1142
粉色の甜心
粉色の甜心 2021-01-30 18:21

I can\'t keep popover the same position on the screen after rotation. Is there any good way to do that, because just setting some frame to popover works terrible after rotating.

13条回答
  •  礼貌的吻别
    2021-01-30 18:58

    UIPopoverController was deprecated in ios9 in favor of UIPopoverPresentationController introduced in ios8. (I went through this transition also when going from UIActionSheet to UIAlertController.) You have two choices (example in obj-C):

    A. Implement the UIViewController method below (UIKit calls this method before changing the size of a presented view controller’s view).

    - (void)viewWillTransitionToSize:(CGSize)size
               withTransitionCoordinator:(id)coordinator {
            [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
            [coordinator animateAlongsideTransition:nil
                                         completion:^(id _Nonnull context) {
                                             // Fix up popover placement if necessary, *after* the transition.
                                             // Be careful here if a subclass also overrides this method.
                                             if (self.presentedViewController) {
                                                 UIPopoverPresentationController *presentationController =
                                                         [self.presentedViewController popoverPresentationController];
                                                 UIView *selectedView = /** YOUR VIEW */;
                                                 presentationController.sourceView = selectedView.superview;
                                                 presentationController.sourceRect = selectedView.frame;
                                             }
                                         }];
        }
    

    B. Alternatively, when configuring your UIPopoverPresentationController to present, also set its delegate. e.g. your presenting vc can implement UIPopoverPresentationControllerDelegate and assign itself as the delegate. Then implement the delegate method:

    - (void)popoverPresentationController:(UIPopoverPresentationController *)popoverPresentationController
              willRepositionPopoverToRect:(inout CGRect *)rect
                                   inView:(inout UIView * _Nonnull *)view {
        UIView *selectedView = /** YOUR VIEW */;
        // Update where the arrow pops out of in the view you selected.
        *view = selectedView;
        *rect = selectedView.bounds;
    }
    

提交回复
热议问题