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;
//这个是返回优先方向
- (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];
}
//这个是返回优先方向
- (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];
}
//这个是返回优先方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}
网友评论
supportedInterfaceOrientationsForWindow:(UIWindow *)window