第一步:
Xcode工程配置中的Device Orientation有四個方向,勾選某個方向,即表示支持該方向的旋轉(zhuǎn)(我這里除了倒置其余三個都選中了)
這一步完成,旋轉(zhuǎn)手機或者模擬器,畫面就會對應(yīng)轉(zhuǎn)換橫豎屏(模擬器模擬轉(zhuǎn)換方向按鍵為:command+上下左右)
第二步:
在AppDelegate中添加方法關(guān)閉橫豎屏切換,方法如下
1.AppDelegate.h中外露一個屬性
@property(nonatomic,assign)BOOL allowRotation;//是否允許轉(zhuǎn)向
2.AppDelegate.m中添加方法(如果屬性值為YES,僅允許屏幕向左旋轉(zhuǎn),否則僅允許豎屏)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskLandscapeLeft;
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
第三步:
1.在需要強制橫屏的控制器.m中添加旋轉(zhuǎn)為橫屏方法
- (void)setNewOrientation:(BOOL)fullscreen
{
if (fullscreen) {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}else{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
}
2.view DidLoad中添加以下代碼
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;//(以上2行代碼,可以理解為打開橫屏開關(guān))
[self setNewOrientation:YES];//調(diào)用轉(zhuǎn)屏代碼
3.重寫導(dǎo)航欄返回箭頭按鈕,拿到返回按鈕點擊事件
- (void)back {
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//關(guān)閉橫屏僅允許豎屏
[self setNewOrientation:NO];
[self.navigationController popViewControllerAnimated:YES];
}