我知道iOS 8现在会针对当前界面方向返回正确的屏幕尺寸。要在iOS 7中获取某个方向的设备宽度,如果方向是横向,则必须返回高度;如果方向是纵向,则必须返回宽度,但是您始终可以在iOS 8中返回该宽度。我正在开发的应用程序将支持iOS 7和8。(请参见下面的代码)
但是,我注意到了另一个区别。如果我调用此方法并传递其方向(从中获取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;
}
用例:
运行iOS 7的iPad:
[self screenWidthForOrientation:[UIApplication sharedApplication].statusBarOrientation]
的viewDidAppear
返回正确的宽度[self screenWidthForOrientation:toInterfaceOrientation]
的willRotateToInterfaceOrientation:toInterfaceOrientation:duration
返回正确的宽度运行iOS 8的iPad:
[self screenWidthForOrientation:[UIApplication sharedApplication].statusBarOrientation]
的viewDidAppear
返回正确的宽度[self screenWidthForOrientation:toInterfaceOrientation]
会willRotateToInterfaceOrientation:toInterfaceOrientation:duration
返回错误的宽度(旋转发生前当前的宽度)这是我的代码,用于在应用约束之前为iOS7 / iOS8计算正确的宽度和高度。
- (void) applyConstraints:(UIInterfaceOrientation)toInterfaceOrientation
{
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat heightOfScreen;
CGFloat widthOfScreen;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
// iOS 8.0 and later code here
if ([UIApplication sharedApplication].statusBarOrientation == toInterfaceOrientation) {
heightOfScreen = screenSize.height;
widthOfScreen = screenSize.width;
} else {
heightOfScreen = screenSize.width;
widthOfScreen = screenSize.height;
}
} else {
if (UIDeviceOrientationIsLandscape(toInterfaceOrientation)) {
heightOfScreen = screenSize.width;
widthOfScreen = screenSize.height;
} else {
heightOfScreen = screenSize.height;
widthOfScreen = screenSize.width;
}
}
//Applying new constraints
...
}
它不是很漂亮,但是可以工作=)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句