封装工具类
OrientationUtil.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface OrientationUtil : NSObject
/**
* 切换横竖屏
*
* @param orientation :UIInterfaceOrientation
*/
+ (void)forceOrientation: (UIInterfaceOrientation)orientation;
/**
* 判断是否竖屏
*
* @return 布尔值
*/
+ (BOOL)isOrientationLandscape;
@end
OrientationUtil.m
#import "OrientationUtil.h"
@implementation OrientationUtil
+ (void)forceOrientation: (UIInterfaceOrientation)orientation {
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget: [UIDevice currentDevice]];
int val = orientation;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
+ (BOOL)isOrientationLandscape {
// if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
return YES;
} else {
return NO;
}
}
@end
使用
ViewController.m
#import "ViewController.h"
#import "OrientationUtil.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)orientationPortrait:(UIButton *)sender {
if ([OrientationUtil isOrientationLandscape]) {
[OrientationUtil forceOrientation:UIInterfaceOrientationPortrait];
}
}
- (IBAction)orientationLandscapeLeft:(UIButton *)sender {
if (![OrientationUtil isOrientationLandscape]) {
[OrientationUtil forceOrientation:UIInterfaceOrientationLandscapeLeft];
}
}