强制横屏或者竖屏
应用中可能会遇到在某个页面强制显示横屏或者竖屏的需求。然鹅,系统默认的 只有你在当前页面改变了横竖屏的状态时(也就是 有横屏转为竖屏 或者 竖屏转为横屏的操作)才会触发横竖屏、改变横竖屏。
现在,我们怎么才能进入或者从某个页面退出 就默认设置当前页面强制变为横屏或者竖屏?
需要的方法
1、
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window 用于更改横竖屏的状态 返回的是枚举
2、
更改UIDevice中的 key 为 @“
orientation” 的值
具体实现:
1、 在AppDelegate.h中 声明一个BOOl 值 isAllowRotation 用于控制当前页面 横竖屏的状态
然后实现
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
if (self.isAllowRotation == YES) {
//横屏 return UIInterfaceOrientationMaskLandscape;
}else{
//竖屏 return UIInterfaceOrientationMaskPortrait;
}
}
2、添加UIDevice 的 分类 并 实现更改 orientation 的value
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
最后 在需要的地方 调用
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; //允许转成横屏
appDelegate.isAllowRotation = YES; //调用横屏代码
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight]; }
BTW
改变横竖屏的方法是有动画的, 可以在viewDidAppear 中调用。或者 为了更好的感官 可以在 推出 或者 推入的方法调用之前 调用更改横竖屏的方法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南