Reputation: 3444
I have a project I created in XCode 4 that runs on the iPad and iPhone. When the display is rotated I was wondering what the best approach is to have the controls rotate as well. Some of my images and controls will need to change as well as the to support the different orientation.
Ideally I would like to have a seperate nib file but I am not sure how to switch the view. I know I can get the orientation through UIInterfaceOrientation and the like, but since I am new to iDevelopment, I am not sure the best way to do this.
Any advice and/or examples would be helpful!!
Thanks, Tony
Upvotes: 0
Views: 1276
Reputation: 100602
Things you probably know already: do as much as you can using the automatic resizing masks. In an ideal world, you'd do everything with them. There are plenty of cases where you can, though it's not hard to think of examples of controllers where you want more control and you obviously have. In code terms, the obvious thing is to implement shouldAutorotateToInterfaceOrientation
and make sure you return 'YES' for supported orientations.
Beyond that, the main thing you want to implement is - willAnimateRotationToInterfaceOrientation:duration:. That'll be called within an animation block when the view is going to rotate, and will be used to give instant effect any time you're coming into a view controller at an orientation it wasn't in previously. Reposition and/or change what's on your view in there, and you'll get a properly animated transition as you desire. For the purposes of decent animation, it's much better to reconfigure one view rather than to switch from one to another.
Cut down (and reformatted for the thin text area here on StackOverflow) example code from a project I have:
- (void)willAnimateRotationToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
{
if(UIInterfaceOrientationIsPortrait(toInterfaceOrientation))
{
nameField.frame = CGRectMake(75, 107, 225, 31);
nameLabel.frame = CGRectMake(20, 107, 47, 32);
URLField.frame = CGRectMake(75, 145, 225, 31);
URLLabel.frame = CGRectMake(20, 145, 47, 32);
}
else
{
nameField.frame = CGRectMake(75, 107, 155, 31);
nameLabel.frame = CGRectMake(20, 107, 47, 32);
URLLabel.frame = CGRectMake(250, 107, 35, 32);
URLField.frame = CGRectMake(293, 107, 167, 31);
}
}
Class outlets connect to a couple of labels and text fields, allowing the user to enter a name and a URL. The effect of that code is that the view switches from one column to two columns depending on landscape or portrait.
It's a bind having to hard code positions like that, but I've yet to find a better way. If you're not worried about animated shuffling, a more visual way might be just to set up the two views separately within a NIB and add/remove the relevant one when the moment occurs.
Upvotes: 2