最近做項目遇到一個需求副瀑,就是大部分頁面都是豎屏,只有兩個頁面是橫屏恋谭,這就要用到強制旋轉屏幕了糠睡。我查了網上的資料,人云亦云者眾多疚颊,但是真正有效的很少狈孔,所以干脆我自己總結一個吧,demo見底部材义,文章里所有代碼和設置都是demo里的均抽。
第一步:設置項目屬性為只允許豎屏
需要注意的是,iPad需要在info.plist里設置:
第二步:AppDelegate里的代碼
在 AppDelegate.h里面:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (assign , nonatomic) BOOL isForceLandscape;
@property (assign , nonatomic) BOOL isForcePortrait;
@end
在 AppDelegate.m里面:
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
if (self.isForceLandscape) {
//這里設置允許的橫屏類型
return UIInterfaceOrientationMaskLandscapeRight;
}else if (self.isForcePortrait){
return UIInterfaceOrientationMaskPortrait;
}
return UIInterfaceOrientationMaskPortrait;
}
第三步:在控制器里的代碼其掂,demo是寫在控制器的基類BaseViewController里的
在 BaseViewController.h里聲明:
@interface BaseViewController : UIViewController
//強制橫屏
- (void)forceOrientationLandscape;
//強制豎屏
- (void)forceOrientationPortrait;
@end
在 BaseViewController.m里實現:
//強制橫屏
- (void)forceOrientationLandscape {
AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
appdelegate.isForceLandscape=YES;
appdelegate.isForcePortrait=NO;
[appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
//強制翻轉屏幕油挥,Home鍵在右邊。
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
//刷新
[UIViewController attemptRotationToDeviceOrientation];
}
//強制豎屏
- (void)forceOrientationPortrait {
AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
appdelegate.isForcePortrait=YES;
appdelegate.isForceLandscape=NO;
[appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
//設置屏幕的轉向為豎屏
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
//刷新
[UIViewController attemptRotationToDeviceOrientation];
}
第四步:使用款熬,demo里是Test1ViewController 使用橫屏深寥,TestViewController 使用豎屏:
在 Test1ViewController里使用強制橫屏:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// 強制橫屏
[self forceOrientationLandscape];
}
在 TestViewController里使用強制豎屏:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//強制旋轉豎屏
[self forceOrientationPortrait];
}