一.指定某個(gè)頁面橫屏豎屏。
系統(tǒng)支持橫屏順序
默認(rèn)讀取plist里面設(shè)置的方向(優(yōu)先級(jí)最低)
application設(shè)置的級(jí)別次之
然后是UINavigationcontroller
級(jí)別最高的是UIViewController
例如:A界面跳轉(zhuǎn)到B界面,A界面是豎屏的,B界面進(jìn)入就要橫屏。
方案一:
1.首先設(shè)置項(xiàng)目 支持的屏幕方向
如果不選擇左或者右那么頁面想要左右橫屏都是不可能的,先全局設(shè)置橫屏能力。

2.在項(xiàng)目繼承了UINavigationController的子類CusNavigationController中重寫方法:shouldAutorotate和supportedInterfaceOrientation
//支持旋轉(zhuǎn)
-(BOOL)shouldAutorotate
{
return [self.topViewController shouldAutorotate];
}
//支持的方向
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
3.界面A中,重寫旋轉(zhuǎn)方法 和 支持的方向
-(BOOL)shouldAutorotate
{
return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
4.界面A跳轉(zhuǎn)界面B的方法
ViewController2 * vc=[[ViewController2 alloc]init];
[self presentViewController:vc animated:YES completion:nil];
//[self.navigationController pushViewController:vc animated:YES];
5.界面B重寫 旋轉(zhuǎn)方法 和 支持的方向
-(BOOL)shouldAutorotate
{
return YES;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft;
}
//一開始的方向
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationLandscapeLeft;
}
這個(gè)方式有個(gè)缺點(diǎn)就是跳轉(zhuǎn)方式只能是model生效,push不生效。
補(bǔ)充說明:測試發(fā)現(xiàn)如果打開鎖屏功能,之前不實(shí)現(xiàn)兩個(gè)繼承的shouldAutorotate和supportedInterfaceOrientations方法的頁面會(huì)出現(xiàn)不適配的橫屏問題。解決方法就是在CusNavigationController的shouldAutorotate方法中返回NO,保證所有ViewController都是不可旋轉(zhuǎn)的。A頁面可以不重寫這兩個(gè)方法,B頁面支持旋轉(zhuǎn)就行。
方案二:
利用KVC調(diào)用私有方法-橫屏
if([[UIDevice currentDevice]respondsToSelector:@selector(setOrientation:)])
{
SEL seletor=NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation=[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:seletor]];
[invocation setSelector:seletor];
[invocation setTarget:[UIDevice currentDevice]];
int val=UIInterfaceOrientationLandscapeRight;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
二.監(jiān)聽橫豎屏狀態(tài)并適配UI
使用通知監(jiān)聽
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:UIDeviceOrientationDidChangeNotification object:nil];
監(jiān)聽方法
-(void)change:(NSNotification*)notification
{
CGFloat width=[UIScreen mainScreen].bounds.size.width;
CGFloat height=[UIScreen mainScreen].bounds.size.height;
if(width/height<1.0)
{
NSLog(@"豎屏");
placeView.frame=CGRectMake(0, 0, 50, self.view.frame.size.height);
}else
{
NSLog(@"橫屏");
placeView.frame=CGRectMake(0, 0, 100, self.view.frame.size.height);
}
}
三.強(qiáng)制橫屏其實(shí)就暴力的一句
if(self.isScreenRight)
{
[[UIDevice currentDevice]setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
}else
{
[[UIDevice currentDevice]setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
}