从window.rootViewController根视图一层一层返回,直到最上层,从最上层设置是否支持.
当初 电影时光 一直想加进去,在视频播放时横屏,其他竖屏. 现在是会了. 真机测试的时候一定要把设置里的屏幕锁定去掉.
1. AppDelegate中 (这个方法可不写,会有默认的实现, 推荐不写)
- (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return UIInterfaceOrientationMaskAll;
}
2. UITabBarController中设置
- (BOOL)shouldAutorotate
{
return [self.selectedViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.selectedViewController supportedInterfaceOrientations];
}
3. UINavigationController中设置
- (BOOL)shouldAutorotate
{
return [self.topViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
某个页面如果不支持
- (BOOL)shouldAutorotate
{
return NO;
}
某个页面如果支持
- (BOOL)shouldAutorotate
{
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
/**刚进入时的方向*/
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationMaskAll; // 全屏幕
return UIInterfaceOrientationMaskPortrait ; //正向
}
/**
屏幕旋转的调用函数
*/
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
// 即将开始旋转
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
// 旋转中
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
// 旋转结束
}];
}
//获取当前 状态栏的方向
[[UIApplication sharedApplication] statusBarOrientation]
本段代码参考: iOS设置某个界面强制横屏,进入就横屏 - 爱生活爱代码 - 博客园
//setOrientation 在3.0以后变为私有方法了,不能直接去调用此方法,否则后果就是被打回。
在网上搜了很多很久,都是这种调用私有方法的:
//强制横屏,会被打回。
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
[[UIDevice currentDevice] performSelector:@selector(setOrientation:)
withObject:(id)UIInterfaceOrientationLandscapeRight];
}
不能直接调用,但是可以间接的去调用,下面的方法就是利用 KVC 机制去间接调用,多次验证不会被打回,放心!
-(void)viewWillAppear:(BOOL)animated{
NSNumber *orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}