LibGDX iOS端:如何通过RoboVM编程实现屏幕旋转
Hey there! Let's work through this screen rotation problem you're hitting. First off, the approach you tried directly modifying the UIDevice's orientation via KeyValueCoder has two main issues: it relies on a private API pattern that Apple might reject, and you're running into NSObject-related headaches because you're using the wrong method for setting the value. Here's the proper way to handle this in a Java-based iOS project (like with RoboVM):
Step 1: Configure Your ViewController to Support the Target Orientation
First, make sure your ViewController allows rotation to the landscape orientation you want. Override these two methods in your ViewController class:
@Override public boolean shouldAutorotate() { return true; // Enable auto-rotation for this VC } @Override public UIInterfaceOrientationMask getSupportedInterfaceOrientations() { // Allow Landscape Left (adjust to your needs, e.g., add LandscapeRight if needed) return UIInterfaceOrientationMask.LandscapeLeft; }
Step 2: Trigger Rotation at Your Game's Target Stage
When you reach the part of your game where you want the screen to rotate, you don't need to hack the UIDevice directly. Instead, tell the system to update the supported orientations and trigger the rotation:
// Get a reference to your main ViewController (adjust this based on your app's structure) UIViewController mainVC = UIApplication.getSharedApplication().getKeyWindow().getRootViewController(); // Tell the system the supported orientations have changed mainVC.setNeedsUpdateOfSupportedInterfaceOrientations();
If you absolutely need to force the rotation immediately (note: this uses a semi-private approach, so test carefully for App Store compliance), you can use this instead:
UIDevice.getCurrentDevice().setValueForKey( NSNumber.valueOf(UIInterfaceOrientation.LandscapeLeft.value()), new NSString("orientation") );
This avoids the KeyValueCoder issue because we're using the standard setValueForKey method inherited from NSObject (which UIDevice extends in RoboVM).
Key Notes
- Avoid direct UIDevice orientation modifications if possible—Apple prefers letting the system handle rotation based on your ViewController's supported orientations. This keeps your app compliant and avoids unexpected behavior.
- Make sure you have a valid reference to your active ViewController when triggering the rotation. If your game uses multiple VCs, adjust the
mainVClookup to target the correct one.
内容的提问来源于stack exchange,提问作者icarumbas

