iOS 强制横屏或强制竖屏

2019-10-09  本文已影响0人  浅宇落

灵活设置横竖屏,不用区分Push还是Present,都是可以设置。

第一步

勾选方向.png

AppDelegate.h中添加旋转属性

/** 是否允许转向 */
@property(nonatomic,assign) BOOL allowRotation;

AppDelegate.m中添加转屏的代理方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
    
    if (self.allowRotation == YES) {
        //横屏
        return UIInterfaceOrientationMaskLandscape;
        
    }else{
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
        
    }
}

第二步

设置横竖屏的核心方法,我是直接把这个方法添加到了UIDevice的分类中,代码如下:

UIDevice+TFDevice.h

#import <UIKit/UIKit.h>
@interface UIDevice (TFDevice)
/**
 * @interfaceOrientation 输入要强制转屏的方向
 */
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end

UIDevice+TFDevice.m

#import "UIDevice+TFDevice.h"
 
@implementation UIDevice (TFDevice)
 
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
        
 NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
 [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
 NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
 [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
}
@end

第三步

在需要设置横屏的控制器的ViewDidLoad中添加下面代码:

- (void)viewDidLoad {
    [super viewDidLoad];
 
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //允许转成横屏
    appDelegate.allowRotation = YES;
    //调用横屏代码
    [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];

    // 屏幕常亮(不然会息屏)
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

需要注意的是push过去的时候变成横屏,pop出去的时候在设置竖屏,此时最好禁用系统的侧滑返回手势。

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

push控制器:

//点击导航栏返回按钮的时候调用,所以Push出的控制器最好禁用侧滑手势:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
//切换到竖屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
   
[self.navigationController popViewControllerAnimated:YES];

// 还原
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];

present控制器:

AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
//切换到竖屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
    
[self dismissViewControllerAnimated:YES completion:nil];

// 还原
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];

到此大功告成, 快试试效果吧.

上一篇 下一篇

猜你喜欢

热点阅读