iOS屏幕旋转
1.基本属性和概念
- shouldAutorotate </br>
Returns a Boolean value indicating whether the view controller'��s contents should auto rotate.
控制器的内容是否自动旋转
- supportedInterfaceOrientations </br>
Returns all of the interface orientations that the view controller supports.
控制器支持的选装方向
注意:
UIDeviceOrientation 设备方向
UIInterfaceOrientation 屏幕视图方向
竖屏时设备方向和屏幕方向是一致的
横屏时设备方向和屏幕方向相反,如手机右转(home键在右侧)时,屏幕方向是左转的。
有部分三方没有及时升级 屏幕旋转后 View显示反了
- preferredInterfaceOrientationForPresentation
Returns the interface orientation to use when presenting the view controller.
present View Controller 优先显示的方向
根控制器控制视图的是否支持自动旋转和旋转方向
即根控制器是UINavigationController
- (BOOL)shouldAutorotate
{
return [self.topViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.topViewController preferredInterfaceOrientationForPresentation];
}
2、场景: 项目一直竖屏,现在有一个界面想横屏
第一种Push的方式
第一步:Device Orientaion中勾选Landscape Left 和 Landscape Right
第二步:基类VC自动旋转和支持方向的方法
//根视图默认不支持自动旋转
- (BOOL)shouldAutorotate
{
return NO;
}
// 支持竖屏显示方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
第三步:在目标VC界面
//目标视图支持自动旋转
- (BOOL)shouldAutorotate
{
return YES;
}
// 支持竖屏显示方向 -> UIInterfaceOrientationMaskLandscape
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscape;
}
第四步:目标VC界面添加
//强制转屏
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
//转屏后回调
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator NS_AVAILABLE_IOS(8_0)
{
// NSLog(@"%d",[NSThread isMainThread]);
// NSLog(@"%@",NSStringFromCGSize(size));
// 记录当前是横屏还是竖屏
// 翻转的时间
CGFloat duration = [coordinator transitionDuration];
[UIView animateWithDuration:duration animations:^{
//转屏后刷新UI坐标
[self reloadLandscapeView:size];
}];
}
第二种present的方式
第一步:同上
第二步:同上 基类VC多添加一个方法
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
第三步:同上 目标VC多添加一个方法
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscapeLeft;
}
第四步:目标VC界面重写方法
- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator NS_AVAILABLE_IOS(8_0);
{
[super willTransitionToTraitCollection:newCollection
withTransitionCoordinator:coordinator];
[self reloadLandscapeView:CGSizeMake(MAX(self.view.frame.size.width, self.view.frame.size.height), MIN(self.view.frame.size.width, self.view.frame.size.height))];
}