在Qt中通过原生Objective-C实现仅程序化屏幕旋转的问题
在Qt iOS中禁止手动屏幕旋转,仅保留程序化控制
问题背景
已通过Objective-C实现程序化屏幕旋转功能,代码如下:
UIInterfaceOrientation toIOSOrientation(ScreenOrientation desiredOrientaion) { if (desiredOrientaion == ScreenOrientation::Landscape || desiredOrientaion == ScreenOrientation::LandscapeReversed) { return UIInterfaceOrientation::UIInterfaceOrientationLandscapeLeft; } else if (desiredOrientaion == ScreenOrientation::Portrait) { return UIInterfaceOrientation::UIInterfaceOrientationPortrait; } else { return UIInterfaceOrientation::UIInterfaceOrientationPortrait; } } void iOSTools::changeOrientation(ScreenOrientation desiredOrientaion) { NSNumber* value = [NSNumber numberWithInt:toIOSOrientation(desiredOrientaion)]; [[UIDevice currentDevice] setValue:value forKey:@"orientation"]; [UIViewController attemptRotationToDeviceOrientation]; }
同时在Info.plist中配置了支持的屏幕方向:
<key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> </array>
但目前用户仍可手动切换屏幕方向,需要通过重写shouldAutorotate方法禁止手动旋转,仅保留程序化控制能力。
实现方案
在Qt iOS项目中,需通过Objective++混编重写Qt底层的UIViewController方法,具体步骤如下:
1. 创建Objective++扩展文件
新建一个.mm后缀的文件(比如QtIOSOrientationLock.mm),编写iOS原生代码扩展:
#import <UIKit/UIKit.h> // 为Qt的iOS主ViewController添加类别,重写旋转控制方法 @interface UIViewController (QtOrientationLock) @end @implementation UIViewController (QtOrientationLock) // 禁止自动旋转(阻止用户手动触发的屏幕转动) - (BOOL)shouldAutorotate { return NO; } // 保留配置中支持的方向,确保程序化旋转可正常生效 - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft; } @end
2. 配置项目编译
将该.mm文件添加到Qt项目的.pro编译配置中:
OBJECTIVE_SOURCES += QtIOSOrientationLock.mm
项目启动时会自动加载这个类别,覆盖原有的旋转逻辑。
3. 验证效果
保留原有的程序化旋转代码,此时用户手动旋转设备时屏幕不会跟随转动,但调用iOSTools::changeOrientation方法仍可正常切换屏幕方向。
内容的提问来源于stack exchange,提问作者Ghorm
相关产品推荐
相关产品推荐

