ios一句代码搞定屏幕旋转

663 阅读1分钟
我们项目中经常用到屏幕旋转功能,为此我封装了一个文件,希望能帮助大家。



 .h文件:

#import <UIKit/UIKit.h>

@interface LSLRotationManager : NSObject 

@property (nonatomic, readonly) UIInterfaceOrientationMask interfaceOrientationMask; @property (nonatomic) UIDeviceOrientation orientation; 

 + (instancetype)defaultManager;

 @end 

 .m文件  

#import "LSLRotationManager.h"

#import <objc/message.h>


static LSLRotationManager *INSTANCE = nil;


@interface LSLRotationManager ()


@property (nonatomic, readwrite) UIInterfaceOrientationMask interfaceOrientationMask;


@end


@implementation LSLRotationManager


#pragma mark - singleton

+ (instancetype)defaultManager {

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

INSTANCE = [[super allocWithZone:nil] init];

INSTANCE.interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;

});

return INSTANCE;

}


+ (instancetype)allocWithZone:(struct _NSZone *)zone {

return [self defaultManager];

}


#pragma mark - setter methods

- (void)setOrientation:(UIDeviceOrientation)orientation {

if (_orientation == orientation) return;

if ([UIDevice currentDevice].orientation == orientation) {

//强制旋转成与之前不一样的

[[UIDevice currentDevice] setValue:@(_orientation) forKey:@"orientation"];

}

_orientation = orientation;

UIInterfaceOrientationMask interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;

switch (orientation) {

case UIDeviceOrientationPortrait:

interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;

break;

case UIDeviceOrientationPortraitUpsideDown:

interfaceOrientationMask = UIInterfaceOrientationMaskPortraitUpsideDown;

break;

case UIDeviceOrientationLandscapeRight:

interfaceOrientationMask = UIInterfaceOrientationMaskLandscapeLeft;

break;

case UIDeviceOrientationLandscapeLeft:

interfaceOrientationMask = UIInterfaceOrientationMaskLandscapeRight;

break;

default:

interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;

break;

}

[LSLRotationManager defaultManager].interfaceOrientationMask = interfaceOrientationMask;

//强制旋转成全屏

[[UIDevice currentDevice] setValue:@(orientation) forKey:@"orientation"];

}


调用的时候调用

 [LSLRotationManager defaultManager].orientation = UIDeviceOrientationLandscapeLeft

就ok了