2

I have a landscape only app. The views are designed in IB as landscape (568x320). Yet when I do this:

NSLog(@"view center: %@", NSStringFromCGPoint(self.view.center));

I get this:

view center: {160, 284}

Which is what the center would be in portait mode. This is causing a lot of problems because I want to position things at the center of the view. Why does view think it is in portrait mode, and what's the best way to center something in the view?

Khaled Barazi
  • 8,681
  • 6
  • 42
  • 62
soleil
  • 12,133
  • 33
  • 112
  • 183

1 Answers1

1

Center here refers to the center of the frame. Keep in mind that the frame does not rotate when the device does. Only the bounds inside the frame rotate.

So if you are writing code that is dependent on device orientation, you should use bounds so to get the center (x,y coordinates) of the view, you would use this:

self.view.bounds.size.width/2 and self.view.bounds.size.height/2.

On my iPhone5, I get:

  • (160,274) for center of view in Portrait mode. This makes sense because the full view dimensions in portrait are (320,568). You loose 20 points on the y axis for the status bar.
  • (284,150) for center of view in Landscape mode. This makes sense because the full view dimensions in landscape are (568,320). You loose 20 points on the y axis for the status bar.

My xy references above rotate with the device. So x is always left to right and y is always top to bottom

Khaled Barazi
  • 8,681
  • 6
  • 42
  • 62
  • You could also add a UIView in the background, bound to the edges, and get the center of that `[self.backgroundView.center]`. While the parent view doesn't rotate, the sub views do. – Marcus Adams Mar 05 '13 at 23:11