开发者

Rotating the uiview without IB

In my app all my controls are created in code. I have not used IB for contro开发者_Python百科ls. now i want to rotate the view to landscape mode. I know I have to use the shouldAutorotate method for this purpose.

But since I have not used IB, how can I resize the controls when they are in landscape mode? How can I position them correctly using code only?


In most cases you can get views to resize themselves appropriately just by setting their autoresizingMask property to some combination of:

  • UIViewAutoresizingFlexibleLeftMargin
  • UIViewAutoresizingFlexibleRightMargin
  • UIViewAutoresizingFlexibleTopMargin
  • UIViewAutoresizingFlexibleBottomMargin
  • UIViewAutoresizingFlexibleWidth
  • UIViewAutoresizingFlexibleHeight

For example, let's say you want a view's width to increase when you rotate it to landscape, you want it to maintain the same margins relative to the top, left, and right sides of the screen, and you want its height to remain the same. This means that out of the six attributes above, only the width and bottom margin should be flexible. The other four attributes are fixed. So you would do:

yourView.autoresizingMask = UIViewAutoResizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;

In those rare cases when you can't get the views to behave appropriately using their autoresizingMask property, you can wrap them in a custom view and override that view's layoutSubviews method. This method gets called when the view's frame changes due to autorotation, so you can check [[UIApplication sharedApplication] statusBarOrientation] and update the frames of your subviews manually.


You position them correctly using code the same way you likely positioned them in the original orientation, for example by setting their frame.

As for where in code to do this, check out the various orientation change methods of UIViewController that will be called when the device orientation changes. You could, for example, move/resize the controls in the view within willAnimateRotationToInterfaceOrientation:duration:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜