Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
Tom Hamming Avatar asked Sep 22 '15 14:09

Tom Hamming


2 Answers

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.

like image 198
Rony Rozen Avatar answered Sep 21 '22 17:09

Rony Rozen


Just add in your ViewController next code

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    self.navigationController.preferredContentSize = CGSizeMake(200, self.parentViewController.childViewControllers.lastObject.preferredContentSize.height-100);
}

Here is the video. Hope this is behaviour which you expecting to get.

like image 26
Alexey Bondarchuk Avatar answered Sep 22 '22 17:09

Alexey Bondarchuk