How on earth do I get the actual dimensions of a presented modal view on iPad?

This is the stupidest thing that should be so easy. I simply present a view controller using:

[self presentViewController:settingsView animated:YES completion:^(){
		}];

Then in the code for the view controller being presented, I want to know it's width, which should be stupidly simple using:

const int viewWidth = self.view.frame.size.width;

HOWEVER, this gives me a value that is the same as the parent view's width, yet on iPad at least this view is visibly smaller than the parent/presenting view (as it is hovering over it with the view visible around the edges behind it). I have tried every stupid thing I can find within the parent view and view controller code that mentions margins and insets and whatnot, but nothing seems to give me the actual stupid value of the stupid presented view's visible dimensions! Any ideas? The iPad is on iPadOS 15.3.1, might try installing a newer version and see if this is some bug in this particular version of the OS.

Answered by Frameworks Engineer in 793543022

This is going to be fairly timing dependent, as this is the result of layout, which may not have been done at the point your asking.

In general the best way to get information like this is within the layout of the view whose size you want – so waiting for your view controller to get viewWillLayoutSubviews and then looking at view.bounds.size.width (and note that sizes can be fractional, so you want to be careful with converting to int, if you even need to).

FYI updated iPad to iPadOS 17.5.1, still getting the wrong view width via self.view.frame.size.width

Could you show the complete code so that we can better understand what happens (it would even be better to have a reproductible example) ?

Maybe self in self.view.frame.size.width is just referring to the parent view and not settingsView.

You could also try

  • const int viewWidth = settingsView.view.frame.size.width;
  • or get the width in the completion handler, to be sure you refer to the correct object.
Accepted Answer

This is going to be fairly timing dependent, as this is the result of layout, which may not have been done at the point your asking.

In general the best way to get information like this is within the layout of the view whose size you want – so waiting for your view controller to get viewWillLayoutSubviews and then looking at view.bounds.size.width (and note that sizes can be fractional, so you want to be careful with converting to int, if you even need to).

Holy moly, I never in a million years would've guessed that viewDidLoad would not have the correct view dimensions set up in time to layout stuff from there. Putting my code in viewWillLayoutSubviews worked. What a nightmare API.

How on earth do I get the actual dimensions of a presented modal view on iPad?
 
 
Q