ios一句程式碼搞定螢幕旋轉

lishuanglong521發表於2018-12-06
我們專案中經常用到螢幕旋轉功能,為此我封裝了一個檔案,希望能幫助大家。


ios一句程式碼搞定螢幕旋轉

 .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了 




相關文章