强制转换屏幕方向

引言:

iOS App中大多数页面是只展示竖屏下的效果,但是少部分页面需要支持横竖屏。 比如:视频播放类 APP,肯定不会只有小窗口播放,播放器界面要支持横竖屏切换。


# 一. 前提

想要强制转换到某个方向,前提是: 项目中必须设置支持要旋转的方向。


# 二. 代码实现

- (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;
        // 从2开始是因为0 1 两个参数已经被selector和target占用
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}


# 三. 使用

# 1. 设置屏幕方向:

[self interfaceOrientation:(UIInterfaceOrientationLandscapeLeft)];

# 2. 获取当前屏幕方向:

 UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];