美文网首页
2018-07-16 关于屏幕翻转

2018-07-16 关于屏幕翻转

作者: 北你妹的风 | 来源:发表于2018-07-17 17:31 被阅读7次

实现屏幕翻转的步骤

1、实现继承自UIViewController的方法

//不自动切换

- (BOOL)shouldAutorotate{

    return NO;

}

//支持的方向

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{

    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;

}

2、监听屏幕翻转的通知

  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadView) name:UIDeviceOrientationDidChangeNotification object:nil];

3、实现reloadView方法

- (void)reloadView{

   if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {

       [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];

       [UIView animateWithDuration:0.5f animations:^{

           self.view.transform = CGAffineTransformMakeRotation(0);

           self.view.bounds = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIHGT);

       }];

   }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft){

       [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];

       [UIView animateWithDuration:0.5f animations:^{

           self.view.transform = CGAffineTransformMakeRotation(M_PI_2);

           self.view.bounds = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIHGT);

       }];

   }

}

4、强制翻转,比如点击按钮。此方法会触发通知,同时触发上面的reloadView方法

- (void)changeTheScreen{

    NSNumber*orientationTarget ;

    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait){

        orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];

    }else if([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft){

        orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];

    }

   if(!orientationTarget) {

        orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];

    }

    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];

}

5、移除通知监听

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];

}

相关文章

网友评论

      本文标题:2018-07-16 关于屏幕翻转

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