Automatically Rearrange Your UI on Rotation

Last weekend I’ve started to write my first real iPhone app. At one point I thought that the app worked pretty well in Portrait mode, but it could also work pretty nicely in Landscape mode.

However, I didn’t just want to rotate each view but instead have a different layout of the view. I didn’t want to hardcode all the positions so I though about something along the lines of creating a second xib file that works as a template to arrange the original xib’s views for landscape.

It turns out that this is actually pretty easy. As long as the views are in the same structure in both xib files, one can just traverse the view tree by iterating over the subviews of a view.

I’ve created a class called BSUIViewRearranger. It can be used pretty easily by calling the following code in your view controller:

[BSUIViewRearranger rearrangeView: self.view
                            toMode: toInterfaceOrientation 
                 usingLandscapeNib: @"MainViewLandscape" 
                       portraitNib: @"MainView"
                   controllerClass: [self class]];

 

just put that inside your -willRotateToIntefaceOrientation:duration: method and you’re done. Optionally one can wrap it in a view animation block like so:
[UIView animateWithDuration:duration animations:^(void) {
 // code here
}];

I’ve released the code on github in case someone wants it.

@_karsten_

 

One Response to “Automatically Rearrange Your UI on Rotation”

  1. phoenix96 Says:

    This will be very useful!