Close button on adaptive popover

后端 未结 3 415
别跟我提以往
别跟我提以往 2021-02-05 11:42

In a storyboard I have a root view controller with a button which triggers a \'Present as Popover\' segue to a UINavigationController containing a UITableViewController. I want

3条回答
  •  囚心锁ツ
    2021-02-05 12:09

    Ok, I have managed to get it working. I think my problem was that the popoverPresentationController property traverses up the view controller heirarchy until it finds a view controller with a popoverPresentationController, i.e. if I have a view controller inside a navigation controller inside a popover the view controller popoverPresentationController would go to the nav controller and use it's property. For this to work, the view controller has to be a child of the navigation controller. At all the points I was trying to use the popoverPresentationController, this was not the case, e.g init, viewDidLoad, viewWillAppear. For some reason, willMoveToParentViewController is not called, even though didMove does get called. So I have no idea how to reference popoverPresentationController in a vc inside a nav controller before the ppc delegate methods are called.

    However, you can reference it in the presenting view controller in prepareForSegue, but you do need to explicitly tell it what presentation style to use. Here's my code that works when placed in the presenting view controller:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        UIViewController *dest = segue.destinationViewController;
        dest.popoverPresentationController.delegate = self;
    }
    
    - (void)dismiss {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
    - (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
        return UIModalPresentationFullScreen; // required, otherwise delegate method below is never called.
    }
    
    - (UIViewController *)presentationController:(UIPresentationController *)controller viewControllerForAdaptivePresentationStyle:(UIModalPresentationStyle)style {
        // If you don't want a nav controller when it's a popover, don't use one in the storyboard and instead return a nav controller here
        UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismiss)];
        UINavigationController *nc = (UINavigationController *)controller.presentedViewController;
        nc.topViewController.navigationItem.leftBarButtonItem = bbi;
        return controller.presentedViewController;
    }
    

提交回复
热议问题