最近在做項目時需求是只有在某一個頁面可以橫豎屏來回切換 其他頁面豎屏顯示
遇到的問題是在手機橫屏的狀態(tài)下 打開app 頁面是錯亂的,
下面是我的解決方案
1席吴、在Xcode中進行設置
w1.png
2妓布、在AppDelegate.h中添加旋轉屬性
/**
* 是否允許轉向
*/
@property(nonatomic,assign)BOOL allowRotation; // 是否允許轉向
在AppDelegate.m中添加轉屏的代理方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
// 如果設置了allowRotation屬性,支持全屏
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskAll;
}else{
return UIInterfaceOrientationMaskPortrait;//默認全局不支持橫屏
}
}
3省容、基類navigation代碼:
- (BOOL)shouldAutorotate {
return self.topViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return self.topViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return self.topViewController.preferredInterfaceOrientationForPresentation;
}
4、項目里寫了一個公共的UIViewController变隔,名字為BaseViewController,創(chuàng)建的BaseViewController繼承UIViewController 在該viewController里進行了如下設置:
-(BOOL)shouldAutorotate{
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
-(BOOL)shouldAutorotate這個方法是重點 如果設置為NO,在橫屏手機的狀態(tài)下打開app頁面還是錯亂的
5右遭、如果你的應用的根控制器是TabVC,就把下面這段代碼放到TabVC根控制器下乖杠,
- (BOOL)shouldAutorotate{
return self.selectedViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return self.selectedViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return self.selectedViewController.preferredInterfaceOrientationForPresentation;
}
這里就實現(xiàn)了橫屏狀態(tài)下打開app豎屏展示的效果分扎。
如果想在某一個頁面里進行橫豎屏切換,可以進行如下設置
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[SimplifyAnswerAppDelegate sharedInstance].allowRotation = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[SimplifyAnswerAppDelegate sharedInstance].allowRotation = NO;
}
[SimplifyAnswerAppDelegate sharedInstance]
是我在appdelegate里面寫的一個類方法胧洒,SimplifyAnswerAppDelegate
是我把appDelegate進行了重新命名畏吓,具體方法實現(xiàn)如下:
+ (SimplifyAnswerAppDelegate *)sharedInstance {
return (SimplifyAnswerAppDelegate *)[UIApplication sharedApplication].delegate;
}
如果是用的APPDelegate,可以這么寫
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO; // 關閉橫屏僅允許豎屏
到這里就實現(xiàn)了前面說的所有頁面默認豎屏,部分頁面橫屏顯示的需求卫漫。