2014-11-09 32 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是不旋轉的座標空間)。

相關問題