Search code examples
iosobjective-cscreen-orientationuiinterfaceorientation

Different portrait and landscape layouts


I am trying to get a handle on layouts in Xcode. I can't seem to find an article that is written well enough for my feeble mind to follow. I have 10 years programming experience but just got into Objective-C. I need some tutorials on dealing with the different views. Seems like they would have put some better tools into developing for a device that rotates by design.

Here is my specific dilemma: The app loads in portrait view and has a few buttons down the side like this:

[Button]

[Button]

[Button]

However, when the device rotates, I would like the buttons to align horizontally like this:

[Button]    [Button]     [Button]

So does anyone have any advice or know of a tutorial to help me accomplish this and as well as get a better grasp of orientations?


Solution

  • The simple answer to your question in this case is: You will have to do this programmatically, or put it in a UICollectionView. UICollectionViews are actually meant for displaying many items and not just three as in your case, so there is really just one thing left: do it in code!

    In the viewController that is handling this part of your app you should run this line somewhere in your viewDidLoad or init methods:

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                          selector:@selector(didRotate:) 
                                          name:UIDeviceOrientationDidChangeNotification                      
                                          object:nil];
    

    This will call the method - (void)didRotate:(NSNotification *)notification

    You could implement this method like this:

    - (void) didRotate:(NSNotification *)notification
    {   
          UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    
           if (orientation == UIDeviceOrientationLandscapeLeft)
          {
            NSLog(@"Landscape Left!");
          }
    }
    

    And put your layout code after you found out which orientation the device has.

    Credits: I borrowed the code from this thread, Thx View rotation notifications: why didRotateFromInterfaceOrientation: doesn't get called?