2014-11-09 61 views
2

我知道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返回不正确的宽度(目前在旋转发生之前的样子)

回答

2

这里是我的代码在应用约束之前计算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 
    ... 
} 

它是不是很漂亮,但它的工作原理=)

0

在iOS系统中8,旋转的整个性质和坐标系统被完全改变。你不应该使用任何事件,如willRotate;他们已被弃用。整个应用程序旋转,包括屏幕。没有更多的旋转变换;整个应用程序(屏幕,窗口,根视图)变得越来越窄,这就是你知道发生了什么事情的原因(或者你可以注册以了解状态栏改变其方向)。如果您想知道坐标,与旋转无关,那么这是新的屏幕坐标空间(fixedCoordinateSpace是不旋转的坐标空间)。

相关问题