美文网首页iOS开发ios实用开发技巧
运用UIDevice类获取屏幕方向

运用UIDevice类获取屏幕方向

作者: luzsyn | 来源:发表于2016-11-28 20:04 被阅读28次

    UIDevice类中,通过orientation属性可以获知6个方向的信息,除了横竖屏4个方向之外,还可以获取到正面朝上,还是正面朝下。
    /UIDeviceOrientation枚举类型/

    typedef NS_ENUM(NSInteger, UIDeviceOrientation) { 
        UIDeviceOrientationUnknown, 
        UIDeviceOrientationPortrait,   // 竖屏,正常状态 
        UIDeviceOrientationPortraitUpsideDown,  // 竖屏,倒置 
        UIDeviceOrientationLandscapeLeft,       // 向左横屏  
        UIDeviceOrientationLandscapeRight,      // 向右横屏
        UIDeviceOrientationFaceUp,              //正面朝上 
        UIDeviceOrientationFaceDown             // 正面朝下
     } 
    

    示例代码

    下方的示例代码,当用户改变手机朝向时,可以在当前屏幕的Label显示当前的朝向。
    (1) 在viewDidLoad方法中,启动方向通知,并在通知中心注册观察者。

    - (void)viewDidLoad {
        [super viewDidLoad];
        UIDevice *device = [UIDevice currentDevice];
        //开启方向改变通知
        [device beginGeneratingDeviceOrientationNotifications];
        //注册方向改变通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];   
    }
    

    (2) 当收到方向改变通知时,调用orientationChange方法,更新Label的文字显示。

    -(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;
         }
     }
    

    (3) 在dealloc方法中注销通知。

    -(void)dealloc {
         //移除观察者
         [[NSNotificationCenter defaultCenter] removeObserver:self];
     }
    

    相关文章

      网友评论

        本文标题:运用UIDevice类获取屏幕方向

        本文链接:https://www.haomeiwen.com/subject/yrnopttx.html