iOS 强制横/竖屏

2018-05-17  本文已影响30人  武一顶顶
强制横竖屏

思路: 不同于自动旋转, 通过单利控制支持方向, 通过Device类强制让设备切换横竖方向

  1. 创建LFInterfaceOrientationManager工具类,管理横竖屏权限
//  支持屏幕旋转工具类

#import <Foundation/Foundation.h>

@interface LFInterfaceOrientationManager : NSObject

//屏幕旋转权限
@property (nonatomic, assign) UIInterfaceOrientationMask faceOrientationMask;
//自动旋转权限
@property (nonatomic, assign) BOOL shouldAutorotate;

+ (instancetype)shareInterfaceOrientationManager;
- (void)makeDevicePortrait;                           //手动竖屏
- (void)makeDevicePortraitRightOrLeft;                //手动横屏

@end


***************************************************

#import "LFInterfaceOrientationManager.h"

@interface LFInterfaceOrientationManager ()

@end

@implementation LFInterfaceOrientationManager


+ (instancetype)shareInterfaceOrientationManager {
    static LFInterfaceOrientationManager *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[LFInterfaceOrientationManager alloc] init];
    });
    return _manager;
}


- (instancetype)init {
    if (self = [super init]) {
        //app默认支持竖屏
        _faceOrientationMask = UIInterfaceOrientationMaskPortrait;
        //暂未配置
        _shouldAutorotate = NO;
    }
    return self;
}

#pragma mark - Private Methods


#pragma mark - Public Methods


#pragma mark - Getters and Setters

- (void)makeDevicePortrait {
    //更新旋转权限
    self.faceOrientationMask = UIInterfaceOrientationMaskPortrait;
    //手动旋转界面方向
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationPortrait] forKey:@"orientation"];
}


- (void)makeDevicePortraitRightOrLeft {
    //更新旋转权限
    self.faceOrientationMask = UIInterfaceOrientationMaskLandscapeLeft |UIInterfaceOrientationMaskLandscapeRight;
    //手动旋转界面方向
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"];
}
@end
  1. appDeleage中添加方法
 //全局控制屏幕方向
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return [LFInterfaceOrientationManager shareInterfaceOrientationManager].faceOrientationMask;
}
  1. 使用demo
#pragma mark - Event Handlers

- (void)rightItemButtonAction:(UIButton *)rightItemButton {
    rightItemButton.selected = !rightItemButton.selected;
    //横屏
    if (rightItemButton.selected) {
        [[LFInterfaceOrientationManager shareInterfaceOrientationManager] makeDevicePortraitRightOrLeft];
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    } else {
        //竖屏
        [[LFInterfaceOrientationManager shareInterfaceOrientationManager] makeDevicePortrait];
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
    [self.scheduleTableView reloadData];
}
上一篇下一篇

猜你喜欢

热点阅读