1、AppDelegate中设置横竖屏开关
.h中
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property(nonatomic, assign) BOOL allowRotation;///允许自由转动屏幕
@property(nonatomic, assign) BOOL allowLandscape;///只允许横屏@end
.m中
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation == 1) {
return UIInterfaceOrientationMaskAll;
} if (self.allowLandscape == 1) {
return UIInterfaceOrientationMaskLandscape;
} return (UIInterfaceOrientationMaskPortrait);
}
2、相关运用
//允许横屏
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate; delegate.allowLandscape = YES;
//强制横屏
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
3、界面返回时记得关闭横屏显示
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate; delegate.allowLandscape = NO;
//返回时强制竖屏
NSNumber *reSetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown]; [[UIDevice currentDevice] setValue:reSetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
4、横竖屏代理(适配屏幕设置)
#pragma mark ------------切换横竖屏后位置更新
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
WWWeakSelf
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
///横屏后的界面frame:
CGSize screen = [UIScreen mainScreen].bounds.size;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
///width > height 则表示横屏显示
if (screen.width > screen.height) {
///相关处理
/// if (orientation == UIInterfaceOrientationLandscapeLeft) ///表示向左的横屏
}
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { }];}
别忘了设置允许APP横竖屏哟
这样 横竖屏相关设置基本就完啦 关灯 下班~~~~~~~~~