实现屏幕翻转的步骤
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];
}
网友评论