iphoneuiviewuiinterfaceorientation

Rotating the uiview without IB


In my app all my controls are created in code. I have not used IB for controls. 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?


Solution

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

    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.