我知道iOS 8现在返回当前界面方向的正确屏幕尺寸。要在iOS 7中获取设备的方向宽度,如果方向为横向,则必须返回高度,如果方向为纵向,则必须返回高度,但您始终可以返回iOS 8中的宽度。我已考虑到我正在开发,将支持iOS 7和8(见下面的代码)调用willRotateToInterfaceOrientation时iOS 7和iOS 8的mainScreen边界大小不同
但是,我注意到另一个区别。如果我调用这个方法并传递它的方向(从willRotateToInterfaceOrientation
获得),那么在iOS 7上,它会返回适当的宽度,但在iOS 8上它会返回旧(当前)方向的宽度。
当我知道当前的方向或将在iOS 8和iOS 7上时,如何获得屏幕宽度?
尽管我可以交换iOS 8的宽度和高度,但当设备未转换到新方向时调用此函数时,会返回错误的值。我可以创建两种不同的方法,但我正在寻找更清洁的解决方案。
- (CGFloat)screenWidthForOrientation:(UIInterfaceOrientation)orientation
{
NSString *reqSysVer = @"8.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
return [UIScreen mainScreen].bounds.size.width;
}
CGRect screenBounds = [UIScreen mainScreen].bounds;
CGFloat width = CGRectGetWidth(screenBounds);
CGFloat height = CGRectGetHeight(screenBounds);
if (UIInterfaceOrientationIsPortrait(orientation)) {
return width;
} else if (UIInterfaceOrientationIsLandscape(orientation)) {
return height;
}
return width;
}
使用案例:
iPad上运行的iOS 7:
- 调用
[self screenWidthForOrientation:[UIApplication sharedApplication].statusBarOrientation]
在viewDidAppear
返回正确的宽度 - 调用
[self screenWidthForOrientation:toInterfaceOrientation]
在willRotateToInterfaceOrientation:toInterfaceOrientation:duration
返回正确的宽度
iPad上运行的iOS 8:
- 调用
[self screenWidthForOrientation:[UIApplication sharedApplication].statusBarOrientation]
在viewDidAppear
返回正确的宽度 - 调用
[self screenWidthForOrientation:toInterfaceOrientation]
在willRotateToInterfaceOrientation:toInterfaceOrientation:duration
返回不正确的宽度(目前在旋转发生之前的样子)