UIDeviceOrientation 和 UIInterfaceOrientation

有时候,我们处理自动布局时,需要获取到屏幕旋转方向:

以下为本人亲测:

UIInterfaceOrientation:

我们需要在- (void)viewDidLoad或其他方法中添加观察者,检测屏幕的旋转:

    // 监听状态栏旋转方向,即屏幕旋转
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didChangeStatusBarOrientationNotification:)
                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];

然后实现方法:

// 监听的是StatusBar
- (void)willChangeStatusBarOrientationNotification:(NSNotification *)notification {
    // 此处我们只介绍常用的三种横竖屏
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait) { // 竖屏
        NSLog(@"竖屏");
    }
    if (orientation == UIInterfaceOrientationLandscapeRight)  {// 横屏(Home键在右边)
        NSLog(@"横屏(Home键在右边");
    }
    
    if (orientation == UIInterfaceOrientationLandscapeLeft) { // 横屏(Home键在左边)
        NSLog(@"横屏(Home键在左边)");
    }
}

此处需要说明一下:屏幕的旋转,枚举值里面的 right/left 是以Home方法为准的!和设备旋转是相反的!

 

UIDeviceOrientation:

同样的,我们需要注册设备旋转的观察者:

    // 设置旋转
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didChangeNotification:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];

实现通知方法:

- (void)didChangeNotification:(NSNotification *)noti {
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
            NSLog(@"竖屏");
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"横屏(Home在右边,设备向左边倒)");
            break;
            
        case UIDeviceOrientationLandscapeRight:
            NSLog(@"横屏(Home在左边,设备向右边倒)");
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"横屏(Home在右边,设备向左边倒)");
            break;
            
        case UIDeviceOrientationFaceUp:
            NSLog(@"屏幕向上");
            break;
            
        case UIDeviceOrientationFaceDown:
            NSLog(@"屏幕向下");
            break;
            
        default:
            break;
    }
}


注:设备旋转时,枚举值里面的方法,指的是设备倒向的方法。

 

小技巧:

1.获取屏幕当前状态栏旋转方法

- (UIInterfaceOrientation)appInterface {
    return [UIApplication sharedApplication].statusBarOrientation;
}

 

2.强制屏幕做出旋转

// 2对应相应的枚举值
[[UIDevice currentDevice] setValue:@"2" forKey:@"orientation"]; 

 

尊重作者劳动成果,转载请注明: 【kingdev】

posted @ 2016-06-06 10:32  Kingdev  阅读(661)  评论(0编辑  收藏  举报