iOS 獲取屏幕方向
建議使用[UIApplication sharedApplication].statusBarOrientation來判斷
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
}else {
}
使用UIDevice來獲取屏幕方向(不推薦,第一次獲取的時候會獲得UIDeviceOrientationUnknown)
UIDeviceOrientation duration = [[UIDevice currentDevice] orientation];
UIDeviceOrientation 枚舉定義如下:
typedef NS_ENUM(NSInteger, UIDeviceOrientation) {
UIDeviceOrientationUnknown,
UIDeviceOrientationPortrait, // Home按鈕在下
UIDeviceOrientationPortraitUpsideDown, // Home按鈕在上
UIDeviceOrientationLandscapeLeft, // Home按鈕右
UIDeviceOrientationLandscapeRight, // Home按鈕左
UIDeviceOrientationFaceUp, // 手機平躺,屏幕朝上
UIDeviceOrientationFaceDown //手機平躺,屏幕朝下
} __TVOS_PROHIBITED;
強制屏幕旋轉
- (void)interfaceOrientation:(UIInterfaceOrientation)orientation {
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = orientation;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
注意
一、需要勾選Device Orientation中的Portrait(豎屏)和其他的Landscape Left(向左橫屏)或者Landscape Right(向右橫屏)

勾選需要的屏幕方向
二、ViewController 里需要實現如下方法:
//是否自動旋轉,返回YES可以自動旋轉
- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;
//返回支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;
//這個是返回優(yōu)先方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0) __TVOS_PROHIBITED;
三、若window的rootViewController 是 UINavigationController,為UINavigationController添加一個分類UINavigationController+Revolve,代碼如下:
//是否自動旋轉,返回YES可以自動旋轉
- (BOOL)shouldAutorotate {
return [self.topViewController shouldAutorotate];
}
//返回支持的方向
- (NSUInteger)supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];
}
//這個是返回優(yōu)先方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return [self.topViewController preferredInterfaceOrientationForPresentation];
}
四、 若window的rootViewController 是 UITabbarController,為UITabbarController添加一個分類UITabbarController+Revolve,代碼如下:
//是否自動旋轉,返回YES可以自動旋轉
- (BOOL)shouldAutorotate {
return [self.selectedViewController shouldAutorotate];
}
//返回支持的方向
- (NSUInteger)supportedInterfaceOrientations {
return [self.selectedViewController supportedInterfaceOrientations];
}
//這個是返回優(yōu)先方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}