如何在Rad Studio Rio(10.3.2)C++ iPhone应用中代码实现按钮触发强制横屏
在Rad Studio Rio 10.3.2 C++中实现iPhone强制横屏切换
我刚好在Rad Studio Rio(10.3.2)的C++多设备项目里处理过类似的iPhone横屏强制切换需求,给你分享下可行的实现方案——直接用Form1->Orientation = Landscape;确实不够,得结合iOS原生API才能绕过系统朝向检测,强制锁定横屏:
步骤1:配置项目的iOS方向权限
首先得在项目设置里放开所有需要的方向权限,不然系统层面会限制切换:
- 打开项目的Project Options,找到iOS -> Application -> Supported Device Orientations
- 勾选Portrait、Landscape Left、Landscape Right(先全选,后续用代码精准控制)
步骤2:编写按钮点击事件代码
在你的Form的cpp文件里,先引入iOS原生头文件:
#include <iOSapi.UIKit.h> #include <FMX.Platform.iOS.h>
然后在按钮的点击事件里写核心逻辑:
void __fastcall TForm1::btnForceLandscapeClick(TObject *Sender) { // 先同步FMX Form的方向设置 this->Orientation = TOrientation::Landscape; // 获取当前Form对应的iOS原生视图控制器 UIViewController* viewController = GetViewController(this); if (!viewController) return; // 限制当前视图控制器仅支持横屏方向 viewController->setSupportedInterfaceOrientations(UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight); // 强制切换到指定横屏方向(可选择LandscapeLeft或LandscapeRight) UIInterfaceOrientation desiredOrientation = UIInterfaceOrientationLandscapeLeft; // 兼容iOS 16及以上版本的API if (@available(iOS 16.0, *)) { [viewController setNeedsUpdateOfSupportedInterfaceOrientations]; [[UIApplication sharedApplication] requestSceneSessionRefresh]; } else { // 旧版本iOS用setValue的方式强制切换 [[UIDevice currentDevice] setValue:@(desiredOrientation) forKey:@"orientation"]; } }
关键说明
- 为什么要结合原生API?因为FMX的
Orientation属性本质上依赖iOS系统的方向许可,只有先让系统允许横屏,再通过原生API强制切换,才能实现不受手机实际朝向影响的锁定效果。 - 如果后续需要切回竖屏,只需要把
supportedInterfaceOrientations改回UIInterfaceOrientationMaskPortrait,再设置desiredOrientation为UIInterfaceOrientationPortrait即可。
内容的提问来源于stack exchange,提问作者relayman357
相关产品推荐
相关产品推荐

