iOS开发之强制横竖屏

步骤和代码

  • 第一步 :Appdelegate文件中设置

#import 

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

//在AppDelegate.h文件中设置两个属性
@property(nonatomic, assign) BOOL isForcePortrait;
@property(nonatomic, assign) BOOL isForceLandscape;

@end

//在AppDelegate.m文件中实现代理方法
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.isForceLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }else if (self.isForcePortrait){
        return UIInterfaceOrientationMaskPortrait;
    }else{
        return UIInterfaceOrientationMaskAll;
    }
}
  • 第二步:设置横竖屏的方法,写在分类中
//UIDevice+TFDevice.h文件
#import 

@interface UIDevice (TFDevice)
//interfaceOrientation 输入要强制转屏的方向
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end

//UIDevice+TFDevice.m文件
#import "UIDevice+TFDevice.h"

@implementation UIDevice (TFDevice)

+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
NSNumber resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@“orientation”];
NSNumber orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@“orientation”];
}
@end

  • 第三步:设置横竖屏
#pragma  mark - 强制横竖屏设置
- (void)forceOrientationLandscape { //强制横屏
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isForcePortrait = NO;
    appDelegate.isForceLandscape = YES;
    [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
}
- (void)forceOrientationPortrait  { //强制竖屏
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isForcePortrait = YES;
    appDelegate.isForceLandscape = NO;
    [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
}

注意

  • 这个在展示控制器的时候需要调用,在dismiss或者pop掉控制器的时候也需要将设置恢复原样。

  • 在第三步上强制横屏的以下这句代码中,后面的旋转方向仅仅是告诉屏幕要往横屏右方向转,至于转完之后屏幕能不能也能横屏左那就要看Appdelegate里面实现的代理方法怎么实现的了...

 [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];

DEMO传送门

参考

iOS强制横屏或强制竖屏

以上!!!

弹钢琴.gif
转自:https://www.jianshu.com/p/32ac0b200931

你可能感兴趣的:(Object,C)