iOS中关闭屏幕旋转功能时如何判断屏幕方向

原文地址:http://www.jianshu.com/p/692e7a490747

在相机强制横屏幕之后,产品又让判断只能横屏时才允许拍照,找了一天,看到了下面的文章,解决了我的烦恼,感谢原文作者。

本来一般情况可以使用通知来做

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
但是,当用户没有开启屏幕旋转功能时,当前设备是无法接收到通知的,原因就是因为你锁定屏幕之后,系统会默认你当前的屏幕状态一直都是你锁屏时的状态。
目前多大数用户的苹果手机基本都有螺旋仪和加速器,我们可以根据这个东西来判断 这时候就需要先引入CoreMotion.frameWork这个框架,这个框架就是来处理螺旋仪和加速器的东西

@property (nonatomic, strong) CMMotionManager * motionManager;

每隔一个间隔做轮询,调用处理函数

- (void)startMotionManager{
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    _motionManager.deviceMotionUpdateInterval = 1/15.0;
    if (_motionManager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                       withHandler: ^(CMDeviceMotion *motion, NSError *error){
                                           [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];

                                       }];
    } else {
        NSLog(@"No device motion on device.");
        [self setMotionManager:nil];
    }
}

根据重力感应来判断目前屏幕方向并可以做对应处理

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x))
    {
        if (y >= 0){
            // UIDeviceOrientationPortraitUpsideDown;
        }
        else{
            // UIDeviceOrientationPortrait;
        }
    }
    else
    {
        if (x >= 0){
            // UIDeviceOrientationLandscapeRight;
        }
        else{
            // UIDeviceOrientationLandscapeLeft;
        }
    }
}

关闭时调用

  [_motionManager stopDeviceMotionUpdates];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值