기술 자료

Unity Engine


Unity Engine


Manage screen orientation in Swift Xcode projects

Configure screen orientation settings in Swift projects.
읽는 시간 2분최근 업데이트: 한 달 전

Configure screen orientation settings in Swift projects.
The Swift Xcode project type strictly enforces the orientation settings you configure in Player Settings. This behavior is different from the Objective-C project type, which allows for more flexibility at runtime.
When you build your project, iOS uses the Allowed Orientations for Auto Rotation settings in
Player Settings

?

to determine which orientations the application supports.
The key difference between the project types is how they handle these settings at runtime:
  • Objective-C Project Type: Allows you to override the initial settings and force any orientation at runtime using the Screen API, even if that orientation is disabled in Player Settings.
  • Swift Project Type: Strictly follows the Player Settings. If an orientation isn't enabled, you can't change to it at runtime. Any attempt to do so is ignored.
For example, if you only enable Landscape Left and Landscape Right in Player Settings:
  • In a Swift project, you can't change to Portrait mode.
  • In an Objective-C project, you can change to Portrait mode using a script.

Use scripts to manage screen orientation

Follow these steps to replicate the screen orientation behavior of an Objective-C project in a Swift project:
  1. Navigate to Edit >
    Project Settings

    ?

    > Player.
  2. Select the iOS tab.
  3. In the Resolution and Presentation section, set the Default Orientation to Auto Rotation.
  4. In the Allowed Orientations for Auto Rotation section, enable all orientations your application might require.
  5. Create a script that limits the allowed autorotation orientations when the application starts. For example, to start in a landscape-only mode, use the following code:
Screen.orientation = ScreenOrientation.AutoRotation;Screen.autorotateToPortrait = false;Screen.autorotateToPortraitUpsideDown = false;Screen.autorotateToLandscapeRight = true;Screen.autorotateToLandscapeLeft = true;
You can then update the flags when you need to adjust the screen's orientation.
For example, the following code changes autorotation orientations to portrait only:
Screen.orientation = ScreenOrientation.AutoRotation;Screen.autorotateToPortrait = true;Screen.autorotateToPortraitUpsideDown = false;Screen.autorotateToLandscapeRight = false;Screen.autorotateToLandscapeLeft = false;
Alternatively, you can force the screen into a single, specific orientation.
Screen.orientation = ScreenOrientation.Portrait;

Additional resources