最近在網(wǎng)上找了很多關(guān)于如何在某一個頁面強制橫屏的資料,但是還是沒有實現(xiàn)預(yù)期的效果。最后經(jīng)過不懈努力嗡善,最終還是找到了一個可以實現(xiàn)這一需求的方法渡蜻。下面就將該方法整理出來术吝,并附帶demo下載计济。供以后在開發(fā)中方便使用。
方法實現(xiàn)部分
在AppDelegate.h中定義一個屬性排苍,如下:
/// 是否允許轉(zhuǎn)向
@property(nonatomic,assign)BOOL allowRotation;
AppDelegate.m中實現(xiàn)橫屏或豎屏的設(shè)置:
///// 如果屬性值為YES沦寂,僅允許屏幕向左旋轉(zhuǎn),否則僅允許豎屏淘衙。
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation == YES) {
// 橫屏
return UIInterfaceOrientationMaskLandscape;
} else {
// 豎屏
return (UIInterfaceOrientationMaskPortrait);
}
}
在UIDevice分類中實現(xiàn)強制轉(zhuǎn)屏传藏,如下:
/// 輸入要強制轉(zhuǎn)屏的方向
/// @param interfaceOrientation 轉(zhuǎn)屏的方向
+ (void)deviceMandatoryLandscapeWithNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
// 將輸入的轉(zhuǎn)屏方向(枚舉)轉(zhuǎn)換成Int類型
int orientation = (int)interfaceOrientation;
// 對象包裝
NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];
// 實現(xiàn)橫豎屏旋轉(zhuǎn)
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
應(yīng)用部分
關(guān)于應(yīng)用部分的代碼,在需要旋轉(zhuǎn)屏幕的地方調(diào)用如下方法:
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 打開橫屏開關(guān)
appDelegate.allowRotation = YES;
// 調(diào)用轉(zhuǎn)屏代碼
[UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationLandscapeRight];
在返回到上一個頁面的時候彤守,如果需要保持原來的豎屏毯侦,那么就應(yīng)該實現(xiàn)對應(yīng)的方法即可:
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
// 關(guān)閉橫屏僅允許豎屏
appDelegate.allowRotation = NO;
// 切換到豎屏
[UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationPortrait];
[self.navigationController popViewControllerAnimated:YES];
好了,代碼的主要實現(xiàn)部分都已經(jīng)完成了具垫,高高興興的進入調(diào)試階段侈离,結(jié)果怎么也不能實現(xiàn)預(yù)期效果。這又是什么原因呢筝蚕,難道是代碼層面還有什么問題沒處理好卦碾?仔細檢查了一下,原來是下面的原因:
QQ20200511-160317.png
沒錯起宽,你只要需要將Requires full screen這個選項鉤上就大功告成了洲胖。