iOS强制某个界面横屏的方法
在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];
}