美文网首页
切换横屏或竖屏

切换横屏或竖屏

作者: WSGNSLog | 来源:发表于2017-03-02 11:21 被阅读28次

封装工具类
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];
    }
}

相关文章

网友评论

      本文标题:切换横屏或竖屏

      本文链接:https://www.haomeiwen.com/subject/stphgttx.html