Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autolayout and UIPopoverController

I created a panel with some subviews in it and used a NSLayoutConstraints to achieve positioning.

I would then display it in a UIPopoverController. Before setting it, I would call [UIView layoutIfNeeded] command to force it to size itself (the overall size is based on the size of an image in it that can be different sizes).

PhotoDisplayPanel *panel = [[PhotoDisplayPanel alloc] initWithPhoto:cell.photo isAddPhoto:cell.isAddPhoto];

DLog(@"BEFORE | panel.frame: %@", panel);

[self.view addSubview:panel];

DLog(@"MIDDLE | panel.frame: %@", panel);

[panel layoutIfNeeded];

DLog(@"AFTER | panel.frame: %@", panel);

log:

DEBUG | -[LoginViewController viewDidLoad] | BEFORE | panel.frame: <PhotoDisplayPanel: 0x7878a3f0; frame = (0 0; 0 0); layer = <CALayer: 0x7878a7e0>>
DEBUG | -[LoginViewController viewDidLoad] | MIDDLE | panel.frame: <PhotoDisplayPanel: 0x7878a3f0; frame = (0 0; 0 0); layer = <CALayer: 0x7878a7e0>>
DEBUG | -[LoginViewController viewDidLoad] | AFTER | panel.frame: <PhotoDisplayPanel: 0x7878a3f0; frame = (-358 -245; 578 289); layer = <CALayer: 0x7878a7e0>>

Previously, I would add the [panel layoutIfNeeded] call before adding it to a view. This worked fine. But with iOS 8.1, they changed how layoutIfNeeded works and if you call it before adding my panel to a view, it freaks out and starts breaking constraints to make it work properly.

My issue is that working with a UIPopoverController, since I can not call layoutIfNeeded my panel has no size, so it uses the popover's default size:

enter image description here

While the panel looks like:

enter image description here

I create the UIPopoverController, set the panel as its view, and then set the preferedContentSize property to the panel's size:

UIViewController *viewController = [[UIViewController alloc] init];
viewController.view = self.currentPanel;
viewController.preferredContentSize = CGSizeMake(self.currentPanel.frame.size.width, self.currentPanel.frame.size.height + 00);

Since the panel has not been sized, it is (0, 0).

My question is now, how can I force my panel to size itself based on the constraints?

like image 771
Padin215 Avatar asked Mar 18 '15 17:03

Padin215


1 Answers

The solution is to calculate the preferredContentSize based on your constraints. Note : Your constraints have to be pinned (left/top/right/bottom) to the view controller view in order to be able to calculate the total width/height of the view.

The way to do it, add these lines in your viewWillAppear:

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

CGSize resultSize = [self.view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
self.preferredContentSize = resultSize;
}
like image 155
Tanguy G. Avatar answered Nov 02 '22 07:11

Tanguy G.