免费开源的iOS开发学习平台

UIDevice类:4-方向传感器orientation

由于通过iPhone设备中的运动传感器,可以得到设备当前的加速度、磁力计以及陀螺仪数据,结合这些传感器提供的数据能够获取设备当前的方向信息。在UIDevice类中,对设备的方向信息进行了一次封装,不需要开发者通过计算传感器数据来获取设备朝向,而是直接通过UIDevice类中的orientation属性即可获取设备当前的朝向信息。

UIDevice中与方向相关的属性

UIDevice类中,通过orientation属性可以获知设备六个方向的信息,除了横竖屏四个方向之外,还可以获取到正反放置的信息。

  • 获取设备朝向信息
@property(nonatomic,readonly) UIDeviceOrientation orientation;
/*UIDeviceOrientation枚举类型*/
typedef NS_ENUM(NSInteger, UIDeviceOrientation) {
    UIDeviceOrientationUnknown,
    UIDeviceOrientationPortrait,            // 竖屏,正常状态
    UIDeviceOrientationPortraitUpsideDown,  // 竖屏,倒置
    UIDeviceOrientationLandscapeLeft,       // 向左横屏
    UIDeviceOrientationLandscapeRight,      // 向右横屏
    UIDeviceOrientationFaceUp,              //正面朝上
    UIDeviceOrientationFaceDown             // 正面朝下
} 
  • 获取设备方向改变通知
UIKIT_EXTERN NSString *const UIDeviceOrientationDidChangeNotification;
  • 当需要获取设备方向改变通知之前,需要提前调用beginGeneratingDeviceOrientationNotifications方法
-(void)beginGeneratingDeviceOrientationNotifications; 
  • 不需要调用设备方向改变通知时,调用该方法关闭通知
- (void)endGeneratingDeviceOrientationNotifications;

示例代码

下方的示例代码实现了,当用户改变手机朝向时,可以在屏幕中的一个UILabel控件中显示当前设备的朝向信息。

  • 在viewDidLoad方法中,启动设备方向改变通知,并在通知中心注册观察者。
- (void)viewDidLoad {
    [super viewDidLoad];
    UIDevice *device = [UIDevice currentDevice];
    //开启方向改变通知
    [device beginGeneratingDeviceOrientationNotifications];
    //注册方向改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];   
}
  • 当收到方向改变通知时,调用orientationChange方法,更新orientationLabel的文字显示。
-(void) orientationChange{
    UIDevice *device = [UIDevice currentDevice];    
    switch (device.orientation) {
        case UIDeviceOrientationPortrait:
            self.orientationLabel.text = [NSString stringWithFormat:@"竖屏/正常"];
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            self.orientationLabel.text = [NSString stringWithFormat:@"竖屏/倒置"];
            break; 
        case UIDeviceOrientationLandscapeLeft:
            self.orientationLabel.text = [NSString stringWithFormat:@"横屏/左侧"];
            break;
        case UIDeviceOrientationLandscapeRight:
            self.orientationLabel.text = [NSString stringWithFormat:@"横屏/右侧"];
            break;
        case UIDeviceOrientationFaceUp:
            self.orientationLabel.text = [NSString stringWithFormat:@"正面朝上"];
            break;
        case UIDeviceOrientationFaceDown:
            self.orientationLabel.text = [NSString stringWithFormat:@"正面朝下"];
            break;           
        default:
            self.orientationLabel.text = [NSString stringWithFormat:@"未知朝向"];
            break;
    }
}
  • 在dealloc方法中移除观察者。
-(void)dealloc {
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

示例代码

https://github.com/99ios/17.1.4