我知道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
返回不正確的寬度(目前在旋轉發生之前的樣子)