美文网首页iOS基础知识IOS精选文集iOS定制view
iOS中关闭屏幕旋转功能时如何判断屏幕方向

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

作者: redihd | 来源:发表于2015-08-12 11:55 被阅读7100次

    本来一般情况可以使用通知来做
    [[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];
    

    手动旋转设备

    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

    相关文章

      网友评论

      • 任梦RM:手机放平都会旋转吗?怎么解决这个问题?
      • 猫猫_a011:看了好多用使用加速度值判断,并不能涵盖所有的旋转角度,还是博主的方法最靠谱!赞
      • jinlei_123:楼主知道怎么判断手机的屏幕旋转功能有没有关闭吗?就是获取当前手机的屏幕旋转功能室打开还是关闭的信息??
        redihd: 目前还不能得知时候开启了方向锁定,所以这就看你们产品的需求了,比如你们产品接受开启锁定之后就不处理,直接使用系统UIDeviceOrientationDidChangeNotification通知即可
        如果想要任何时候都能拿到屏幕方向,就可以只用我上面的方案
        iCHENKE:同问
        He_Define:哥们儿,你找到方法了么?判断手机的旋转功能
      • 被丢掉的咸鱼:手动旋转不行啊 请帮助
      • 奔跑的喔汼:我发送通知通知中心怎么接受不到通知啊?
        277ccd5ab3f3:你是不是把手机的屏幕旋转功能给关掉了
      • L了个Y:NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];z这个不能用吧,大兄弟
        redihd:@文刀洋 我在我的app里面用了不止一处私有的api 并没有审核不过
        这个设置屏幕方向的需求已经去掉了。
        现在我试了一下,还是可以直接设置 起作用还是
        L了个Y:@redihd 私有API用了会审核不通过的啊,何况这个我用了没有效果
        redihd:@文刀洋 这是私有方法,但用了好像也没事。不想用这种的 可以 直接设置UIView.transform
      • Oneruofeng:good idea :+1:

      本文标题:iOS中关闭屏幕旋转功能时如何判断屏幕方向

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