Detect orientation

iOS supports several orientation of device.
We sometimes use specific layout according to device orientation.
This post is for it!

How to detect?

NSNotification supports.
We need to notification sender and observer.

Sample

This sample, “orientation header”.
The header follows orientation top every time.

OrientationTestViewController.h

@interface OrientationTestViewController : UIViewController
@end

OrientationTestViewController.m

@interface OrientationTestViewController ()
@property (nonatomic) UIView *header;
@end

@implementation OrientationTestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    [self.header setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:self.header];
    [self initNotification];
}

#pragma mark - Notification
-(void)initNotification {
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(orientationChanged:)
     name:UIDeviceOrientationDidChangeNotification
     object:[UIDevice currentDevice]];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIDeviceOrientationDidChangeNotification];
}

- (void) orientationChanged:(NSNotification *)note
{
    UIDevice * device = note.object;
    switch(device.orientation)
    {
        case UIDeviceOrientationPortrait:
            self.header.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
            break;
        case UIDeviceOrientationPortraitUpsideDown:
        case UIDeviceOrientationLandscapeLeft:
        case UIDeviceOrientationLandscapeRight:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
            self.header.frame = CGRectMake(0, 0, self.view.frame.size.height, 50);
            break;
        default:
            break;
    };
}
@end