41

Using interface builder in xcode and just one .xib file, how can I create alternate layouts when rotating between landscape and portrait orientations?

See diagram of differing layouts enter image description here

N.b. the green view/area would contain 3 items flowing horizontal in landscape and in portrait those 3 items would flow vertically within the green view/area.

Dave Haigh
  • 4,369
  • 5
  • 34
  • 56
  • Wasn't my answer enough to solve your problem ? – Grzegorz Krukowski Sep 12 '13 at 10:34
  • 1
    Thanks but technically you didnt answer my question, I asked how it can be done with one nib. Plus there's 5 days left on the bounty. I'll wait and see if other people have solutions. Hold tight – Dave Haigh Sep 12 '13 at 10:35
  • 1
    With the introduction of the UIStackView in iOS 9, this kind of layout is very easy. Put the views into stack views, and after the view is loaded, you just flip the orientation of the stack views to either vertical or horizontal depending on the orientation of the screen. The system will take care of all the layout changes for you. – Jake Jan 31 '16 at 23:11
  • @Jake nice. what happens when you use UIStackView on pre iOS9 devices? – Dave Haigh Feb 02 '16 at 15:11
  • @DaveHaigh I assume using UIStackView on pre iOS9 devices will crash the app unless you [check for availability of the class](http://stackoverflow.com/questions/25306561/check-for-class-existence-in-swift) and provide an alternative implementation for pre iOS9 devices – Jake Feb 02 '16 at 21:59
  • @dave - do you still seek the right answer here? I need to know if anyone's still reading before typing it in :) – Fattie Jul 13 '16 at 21:38
  • Joe. Size classes per chance? – Dave Haigh Jul 13 '16 at 21:41

8 Answers8

45

A way to do this is to have three views in your .xib file. The first one is the normal view of your Viewcontroller with no subviews.

Then you create the views for portrait and landscape as you need them. All three have to be root-level views (have a look at the screenshot)

enter image description here

In your Viewcontroller, create 2 IBOutlets, one for the portrait and one for the landscape view and connect them with the corresponding views in the interface builder:

IBOutlet UIView *_portraitView;
IBOutlet UIView *_landscapeView;
UIView *_currentView;

The third view, _currentView is needed to keep track of which one of these views is currently being displayed. Then create a new function like this:

-(void)setUpViewForOrientation:(UIInterfaceOrientation)orientation
{
    [_currentView removeFromSuperview];
    if(UIInterfaceOrientationIsLandscape(orientation))
    {
        [self.view addSubview:_landscapeView];
        _currentView = _landscapeView;
    }
    else
    {
        [self.view addSubview:_portraitView];
        _currentView = _portraitView;
    }
}

You will need to call this function from two different places, first for initialization:

-(void)viewDidLoad
{
    [super viewDidLoad];
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    [self setUpViewForOrientation:interfaceOrientation];
}

And second for orientation changes:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self setUpViewForOrientation:toInterfaceOrientation];
}

Hope that helps you!

MeXx
  • 3,357
  • 24
  • 39
  • thanks MeXx. This seems to be the way to achieve what I asked, in combination with @TomSwift's answer. – Dave Haigh Sep 17 '13 at 07:57
  • 5
    Loading a second view will likely not animate the transformation. Hence it will not give userfeedback about which component moved to which position. – Christian Fries Sep 17 '13 at 08:21
  • 14
    One huge issue is how do you handle IBOutlets? If you have, say the same label on both versions. You can only hook one IBOutlet up to your controller.... – LightningStryk Feb 26 '14 at 18:36
  • I guess the only way to handle outlets from the 2 different views is to have a pointer on the currently used outlet. Then you update the pointer when you switch your layout, just as he do with the _currentView – Imotep Aug 29 '14 at 14:43
  • I have the same problem after dealing landscape/portrait. Is there any link about it? Thank you. – e.ozmen Oct 09 '14 at 10:57
  • I never used .xib files in my code. I always design my view programmatically. I think, designing your view programmatically saves lot of time without using .xib files. – WasimSafdar Jul 25 '16 at 12:55
14

There is no automatic way to support that since it is against Apple design. You should have one ViewController supporting both orientations.

But if you really want to do so you need to reload xib's on rotation events and load different nib files.

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [[NSBundle mainBundle] loadNibNamed:[self nibNameForInterfaceOrientation:toInterfaceOrientation] owner:self options:nil];
    [self viewDidLoad];
}

- (NSString*) nibNameForInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    NSString *postfix = (UIInterfaceOrientationIsLandscape(interfaceOrientation)) ? @"portrait" : @"landscape";
    return [NSString stringWithFormat:@"%@-%@", NSStringFromClass([self class]), postfix];
}

And you create two nib files post-fixed with "landscape" and "portrait".

vinnybad
  • 2,102
  • 3
  • 19
  • 29
Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
  • 1
    this isn't an answer to my original question. but it may be the way that I end up supporting landscape and portrait in my project so thanks for the answer. but I cant award it the bounty sorry – Dave Haigh Sep 17 '13 at 07:58
  • 3
    It may not be the answer you were looking for, but Apple recommends against doing what you're suggesting: https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDeviceOrientationChanges/RespondingtoDeviceOrientationChanges.html#//apple_ref/doc/uid/TP40007457-CH7-SW14 – pinkeerach Jan 09 '14 at 03:10
  • 1
    fyi and others reading this, this was how I achieved different layouts. I loaded in different nib files based on orientation exactly as you suggested. a belated thanks :) – Dave Haigh Aug 29 '14 at 13:51
  • @Grzegorz I am using the approach you provided, Problem is how I can preserve UITextField's text when orientation changes? – viral Sep 04 '14 at 10:37
  • If you are using dynamic layouts and Constrains it should do it automatically. – Grzegorz Krukowski Sep 04 '14 at 15:13
  • @AlwaysThere did you find an answer for the UITextField losing its text issue? Grzegorz are you saying the text (what the user typed in the field) should automatically be preserved, or did you (or I) not understand the problem AlwaysThere is having? – eselk Sep 12 '14 at 21:27
  • @eselk No, I still have that issue pending. If you find any solution, don't forget to post it over here. Please. Thank you. – viral Sep 13 '14 at 05:39
8

I like @MeXx's solution, but it has the overhead of keeping two different view hierarchies in memory. Also, if any subview has state (e.g. color) that changes, you'll need to map that across when you switch hierarchies.

Another solution might be to use auto-layout and swap the constraints for each subview for each orientation. This would work best if you have a 1:1 mapping between subviews in both orientations.

Understandably you want to use IB to visually define the layout for each orientation. Under my plan you'd have to do what @MeXx prescribes, but then create a mechanism to store both sets of constraints once the nib was loaded (awakeFromNib) and re-apply the correct set on layout (viewWillLayoutSubviews). You could throw away the secondary view hierarchy once you scraped and stored its constraints. (Since constraints are view-specific you'd likely be creating new constraints to apply to the actual subviews).

Sorry I don't have any code. It's just a plan at this stage.

Final note - this would all be easier with a xib than a storyboard since in a storyboard it's painful to describe views that live outside of a view controller's main view (which is desirable since otherwise its a PITA to edit). Blach!

TomSwift
  • 39,369
  • 12
  • 121
  • 149
  • thanks Tom. in combination with MeXx's solution I think this might work. I awarded him the bounty as he posted the bulk of the solution. Thanks for the addition – Dave Haigh Sep 17 '13 at 07:59
  • do you have any sample code which illustrates this ? – Kunal Balani Apr 09 '14 at 19:50
  • 1
    The advantage to this method is it should theoretically support transition animations out of the box, since all that is changing are the layout constraints, not the views themselves. – devios1 May 28 '14 at 23:18
  • @devios I just tested a simple label with MeXx's solution and surprisingly, the transition animations work great - I see TomSwift's solution as a tradeoff of less memory use for slower speed. IMHO, MeXx's solution will work fine if we ensure that any state which might change (even GUI attributes) gets propagated up to the model and then back down. Remember that in MVC, we should be able to support any number of views (in this case, a portrait and a landscape) with consistency. – kfmfe04 Dec 13 '14 at 17:50
  • @kfmfe04 That is surprising. I admit I only assumed it wouldn't work. I'd be curious to know how it does though, since you are actually removing a subview and then adding in a totally different view object. I don't see how that could possibly be animated. And I totally agree that under MVC it should be completely natural, but in my experience Apple has not taken strides to support multiple different views for a layout. – devios1 Dec 14 '14 at 21:00
  • 1
    @devios Let me take that back - looking at it more closely, I should really say that the animation happens so quickly that it's hard to tell exactly what is happening - but I think the original widgets are rotated and then the final widgets pop into place. – kfmfe04 Dec 15 '14 at 02:44
  • @kfmfe04 That would make a lot more sense. Thanks for clarifying. – devios1 Dec 15 '14 at 21:28
3

Ya you can sir surely ....

I used to do is by giving frame manually when Device rotates

Whenever device rotates , - (void)viewWillLayoutSubviews get called

for Example - take a UIButton *button in your UIView,

- (void)viewWillLayoutSubviews
   {
       if (UIDeviceOrientationIsLandscape([self.view interfaceOrientation]))
       {
         //x,y as you want
         [ button setFrame:CGRectMake:(x,y,button.width,button.height)];

       }
       else
       {
         //In potrait
          //x,y as you want
         [ button setFrame:CGRectMake:(x,y,button.width,button.height)];


       }

   }

In this way you can place it as you like . Thanks

Please have a look on these images

First image of my xCode XIB UIView which i want in both screen

enter image description here

Now as i want to look this view in landscape too so i went to edit my -(void)viewWillLayoutSubviews

enter image description here

Now the result is like this First image of potrait Screen in Simulator

enter image description here

and this is in Landscape

enter image description here

kshitij godara
  • 1,523
  • 18
  • 30
  • I want to use Interface Builder to create my views – Dave Haigh Sep 17 '13 at 07:55
  • 1
    I dont want to do it programmatically and your example has the same layout in both orientations. – Dave Haigh Sep 18 '13 at 07:49
  • Setting frames explicitly in an autolayout-controlled interface tends to run you into trouble eventually. I recommend adjusting the constraints programmatically instead of the view frames. You can create outlets for your constraints and modify their values from the view controller easily enough. – devios1 May 28 '14 at 23:21
2

Solution with storyboard [ios7]. Inside the main view controller, there is the container view that can include the tab bar controller. Inside the tab bar controller, there are 2 tabs. One tab is for controller with portrait and another is for controller in landscape mode.

The main view controller implements these functions:

#define INTERFACE_ORIENTATION() ([[UIApplication sharedApplication]statusBarOrientation])

@interface MainViewController ()
@property(nonatomic,weak) UITabBarController *embeddedTabBarController;
@end

@implementation MainViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"embedContainer"])
    {
        self.embeddedTabBarController = segue.destinationViewController;
        [self.embeddedTabBarController.tabBar setHidden:YES];
    }
}

- (void) adaptToOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
    {
        [self.embeddedTabBarController setSelectedIndex:1];
    }
    else
    {
        [self.embeddedTabBarController setSelectedIndex:0];
    }
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
{
    [self adaptToOrientation:interfaceOrientation];    
}

- (void) viewWillAppear:(BOOL)animated
{
    [self adaptToOrientation:INTERFACE_ORIENTATION()];
}

The segue link in storyboard should be named "embedContainer".

Assure that container view is resizable to fulfil the parent view, in both cases, landscape and portrait.

Take care about the fact that in the runtime 2 instances of the same controller lives in the same time.

Storyboard


Update: Apple docs for alternate landscape view controller

Krešimir Prcela
  • 4,257
  • 33
  • 46
2

I'd just like to add a new answer to reflect upcoming new features in ios8 and XCode 6.

In the latest new software, Apple introduced size classes, which enable the storyboard to intelligently adapt based on what screen size and orientation you are using. Though I suggest you look at the docs above or the WWDC 2014 session building adaptive apps with UIKit, I'll try to paraphrase.

Ensure size classes are enabled,.

You will notice your storyboard files are now square. You can set up the basic interface here. The interface will be intelligently resized for all enabled devices and orientation.

At the bottom of the screen, you will see a button saying yAny xAny. By clicking this, you can modify just one size class, for instance, landscape and portrait.

I do suggest that you read the docs above, but I hope this helps you, as it uses only one storyboard.

rocket101
  • 7,369
  • 11
  • 45
  • 64
  • thanks, sounds like an actual solution (finally), I'll have a proper read. – Dave Haigh Aug 29 '14 at 13:49
  • @DaveHaigh I do hope it helps. Let me know if you have any questions. – rocket101 Aug 29 '14 at 13:50
  • after reading, it sounds like it will do the job but haven't got the opportunity to try it out yet. once I do i'll let you know – Dave Haigh Sep 01 '14 at 07:51
  • 10
    I've spent some time with the size classes and I do not believe there to be a way to do what is being asked. The problem with size classes is they don't really support any notion of orientation, you can get some of that with for iPhone with the 'compact width, any height' for portrait, and 'any width compact height' for landscape, however for iPad you get 'regular width, regular height' for both orientations. – thisispete Sep 08 '14 at 17:38
1

You can use the library GPOrientation. Here is link

Savitha
  • 561
  • 6
  • 19
1

Resize Programatically

I have an app where I have exactly the same situation. In my NIB I just haven the portrait layout. The other layout is performed programatically. It is not that difficult to specify a few sizes programmatically, so no need to maintain two NIBs.

Note that performing the view change programatically by setting frames will result in an animation (or can easily be made using an animation). This will give the user a valuable feedback about which component moved to which position. If you just load a second view, you will lose this advantage and from a UI perspective I believe loading an alternative view is not a good solution.

Use two ViewControllers

If you like to use two ViewControllers, then Apple describes how to do it in its developer documentation, i.e., you find the answer to you question here: RespondingtoDeviceOrientationChanges.

If you like to do it programatically you may add re-position code in the method didRotateFromInterfaceOrientation.

Example

I added the method to my ViewController:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self adjustLayoutToOrientation];
}

Then implemented the adjustment of the layout. Here is an example (the code is specific to my app, but you can read sizes of superviews and calculate frames of subviews from it.

- (void)adjustLayoutToOrientation
{
    UIInterfaceOrientation toInterfaceOrientation = self.interfaceOrientation;
    bool isIPhone = !([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad);

    [self adjustViewHeight];
    [self adjustSubviewsToFrame: [mailTemplateBody.superview.superview frame]];

    CGRect pickerViewWrapperFrame = pickerViewWrapper.frame;
    if(isIPhone) {
        pickerViewWrapperFrame.origin.x = 0;
        pickerViewWrapperFrame.size.height = keyboardHeight;
        pickerViewWrapperFrame.origin.y = [self view].frame.size.height-pickerViewWrapperFrame.size.height;
        pickerViewWrapperFrame.size.width = [self view].frame.size.width;
    }
    else {
        pickerViewWrapperFrame = pickerView.frame;
    }

// MORE ADJUSTMENTS HERE

}
Christian Fries
  • 16,175
  • 10
  • 56
  • 67
  • this isnt using interface builder – Dave Haigh Sep 17 '13 at 07:59
  • Your question was not precise in this point. I believe that working with UI components programatically is a good alternative and in some situations much better. I would consider reloading an alternative view a bad solution since it will break animations. Doing it programatically will animate the transformation from one view to the other, which is a good user feedback for what is happening. – Christian Fries Sep 17 '13 at 08:18
  • Ah. Sorry. I got that wrong. I thought something like "Based on a layout from interface builder" instead of "(Exclusively) using interface builder". You're right. Your use case is described in the developer documentation https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDeviceOrientationChanges/RespondingtoDeviceOrientationChanges.html – Christian Fries Sep 17 '13 at 15:29