iOS横竖屏切换的小方法
2020-06-16 本文已影响0人
Nulll
一个很简单就能实现iOS设备横竖屏的方法。
通过UIDevice 和 AppDelegate 的-application:supportedInterfaceOrientationsForWindow: 这两个来控制。
1、为UIDevice 添加一个分类,并添加一个方法。
+ (void)zh_switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
//首先设置UIInterfaceOrientationUnknown欺骗系统,避免可能出现直接设置无效的情况
NSNumber *orientationUnknown = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
2、为 AppDelegate 添加一个属性 currentInterfaceOrientation
@property(nonatomic,assign)UIInterfaceOrientationMask currentInterfaceOrientation;
//然后实现如下方法即可以。
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
return self.currentInterfaceOrientation;
}
使用
在需要横屏的地方实现如下事件
//只需要横屏的实现
AppDelegate *appD = (AppDelegate *)[UIApplication sharedApplication].delegate;
//设置需要支持的方向
appD.currentInterfaceOrientation = UIInterfaceOrientationMaskLandscape;
//强制设备为某个方向
[UIDevice zh_switchNewOrientation:(UIInterfaceOrientationLandscapeLeft)];
//只要竖屏的实现
AppDelegate *appD = (AppDelegate *)[UIApplication sharedApplication].delegate;
appD.currentInterfaceOrientation = UIInterfaceOrientationMaskPortrait;
[UIDevice zh_switchNewOrientation:(UIInterfaceOrientationPortrait)];
//所有屏幕方向都需要
AppDelegate *appD = (AppDelegate *)[UIApplication sharedApplication].delegate;
appD.currentInterfaceOrientation = UIInterfaceOrientationMaskAll;
[UIDevice zh_switchNewOrientation:(UIInterfaceOrientationLandscapeRight)];