Search code examples
iosuinavigationcontrolleruipopover

How can I make UIPopoverPresentationController resize on navigation pop?


I'm using UIPopoverPresentationController for popovers in an iOS app. When a navigation controller in a popover pushes a new view controller, the popover resizes to that view controller's preferredContentSize. But when the navigation controller pops a view controller off the stack, the popover does not resize to the previous size. How can I make it do that?

Possible duplicate of this question, but for the modern UIPopoverPresentationController.

Update: See here for example code illustrating the problem. Clone it and run it in an iPad simulator. Tap the Popover button and you get a popover with a nav controller. Tap the Push bar button item and you get a new taller VC on the stack (the size is in the nav bar). Pop and it doesn't resize back down to what it was.


Solution

  • Add this line:

    self.navigationController.preferredContentSize = self.preferredContentSize;
    

    to your viewWillAppear: method, so that it will now look like this:

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        if (self.navigationController)
        {
            UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"Push" style:UIBarButtonItemStylePlain target:self action:@selector(onPush)];
            self.navigationItem.rightBarButtonItem = item;
            self.navigationItem.title = NSStringFromCGSize(self.preferredContentSize);
            self.view.backgroundColor = [UIColor lightGrayColor];
    
            self.navigationController.preferredContentSize = self.preferredContentSize;
        }
    }
    

    It will make sure that the navigation controller's preferred size is updated each time the displayed view controller changes. I tested it on your sample code and it resolved the issue.