第一步:
imageXcode工程配置中的Device Orientation有四个方向,勾选某个方向,即表示支持该方向的旋转(我这里除了倒置其余三个都选中了)
这一步完成,旋转手机或者模拟器,画面就会对应转换横竖屏(模拟器模拟转换方向按键为:command+上下左右)
第二步:
在AppDelegate中添加方法关闭横竖屏切换,方法如下
1.AppDelegate.h中外露一个属性
@property(nonatomic,assign)BOOL allowRotation;//是否允许转向
2.AppDelegate.m中添加方法(如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskLandscapeLeft;
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
第三步:
1.在需要强制横屏的控制器.m中添加旋转为横屏方法
- (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行代码,可以理解为打开横屏开关)
[self setNewOrientation:YES];//调用转屏代码
3.重写导航栏返回箭头按钮,拿到返回按钮点击事件
- (void)back {
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
[self setNewOrientation:NO];
[self.navigationController popViewControllerAnimated:YES];
}
网友评论