React Native에서 회전을 비활성화하는 방법은 무엇입니까?


104

세로보기 만 지원하고 싶습니다. React Native 앱이 자동 회전하지 않도록하려면 어떻게해야합니까? 문서 및 Github 문제 검색을 시도했지만 도움이되는 내용을 찾지 못했습니다.


응용 프로그램 속성에서 지원되는 방향을 설정할 수 없습니까 (다른 iOS 앱과 동일)?
Thilo 2015.08.24

8
Android는 어떻습니까?
ooolala

2

참고 : MOTO 4에서 sensorPortrait제대로 작동하지 못했습니다 . 거꾸로 된 세로 (예 :)는 지원하지 않습니다 reversePortrait. 그러나 사용 fullSensor은 효과가 있었지만 풍경도 허용한다는 경고가있었습니다. 그것은 나를 위해 잘 었죠하지만 당신은 원하는 경우 portraitreversePortrait, 당신은 귀하의 활동의 방향 변경을 차단할 수 있도록 onConfigurationChanged하고 newConfig.orientation그냥 무시하거나 재정의 풍경 변경됩니다.
Joshua Pinter 2019

답변:


133

React Native 앱은 거의 일반적인 iOS 애플리케이션이므로 다른 모든 앱에서와 똑같은 방식으로 할 수 있습니다. 일반 응용 프로그램 속성에서 허용 된 장치 방향으로 "Landscape Left"및 "Landscape Right"를 선택 취소 (XCode에서)하기 만하면됩니다.

장치 방향


고마워! 또 하나의 문제는, 내가 확인 portrait하고 upside down,하지만 난 시뮬레이터의 화면 (90도 회), 문제는 무엇을 회전 할 때 내 응용 프로그램은 자동 회전하지 않았다?
syg

그것을 시도했습니다. iPad (Pro) 시뮬레이터에서 실행할 때 RN 34에서 작동하지 않는 것 같습니다. 그러나 iPhone 시뮬레이터에서 실행할 때는 작동합니다. 그래도 iPad에서 작동하려면 필요합니다. 이상한.
Pedram

1
"장치"를 이전과 같이 "유니버설"이 아닌 iPad로 설정해야합니다. 그게 효과가있었습니다.
Pedram

@Jarek Potiuk 씨는 약간의 의심이 있습니다. 실제로 시뮬레이션 프로그램을 실행했을 때 기본적으로 가로 모드가 표시되며 landscapeleft & right를 사용했습니다. 그러나 지금은 장치에서 가로 모드가 표시되지 않습니다. 나는 반응 네이티브 방향 모듈을 사용하고 있으며 xcode에서 가로 및 오른쪽을 선택합니다. 그러나, 나는하지 않았다
Lavaraju

2
어떤 이유로 더 이상 작동하지 않습니다. 적어도 안react-native 0.45.1
MattyK14 jul.

79

iOS의 경우 Jarek의 대답은 훌륭합니다.

Android의 경우 AndroidManifest.xml 파일을 편집해야합니다. 세로 모드로 잠 그려는 각 활동에 다음 행을 추가하십시오.

android:screenOrientation="portrait" 

따라서 전체 예제는 다음과 같습니다.

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

https://developer.android.com/guide/topics/manifest/activity-element.html 문서에서 사용 가능한 screenOrientation 속성의 전체 목록을 참조하십시오.


2
이것은 완벽하게 작동했습니다. VS Code를 사용하는 다른 사용자를 위해 '명령 팔레트 ...'에서 '장치 / 시뮬레이터에서 Android 실행'을 실행합니다. 기기를 '새로 고침'으로 흔들면 앱이 작동하지 않습니다.
Rishi

66

2017 업데이트 : {"orientation": "portrait"}

현재 많은 공식처럼 기본 가이드 반응 이 하나 만들 때 너무 기존의 답변에 추가 나는 또한 iOS 및 안드로이드 모두 작동 만 필요하기 때문에 가치가 주목할 인 엑스포 관련 솔루션을 추가 할 것입니다 네이티브 응용 프로그램을 엑스포 반응 사용하는 것이 좋습니다 XCode 구성, AndroidManifest.xml 등을 엉망으로 만들 필요없이 한 번 설정하십시오.

빌드시 방향 설정 :

Expo로 React Native 앱을 빌드하는 경우 파일 의 orientation필드를 사용할 수 있습니다. app.json예를 들면 다음과 같습니다.

{
  "expo": {
    "name": "My app",
    "slug": "my-app",
    "sdkVersion": "21.0.0",
    "privacy": "public",
    "orientation": "portrait"
  }
}

그것은 설정할 수 있습니다 "portrait", "landscape"또는 "default"어떤 수단이없는 방향 잠금 자동 회전 할 수 있습니다.

런타임시 방향 설정 :

다음과 같이 실행하여 런타임에 해당 설정을 재정의 할 수도 있습니다.

Expo.ScreenOrientation.allow(Expo.ScreenOrientation.Orientation.LANDSCAPE);

인수는 다음과 같을 수 있습니다.

  • ALL — 가능한 4 가지 방향
  • ALL_BUT_UPSIDE_DOWN — 반전 세로를 제외한 전부는 특정 Android 장치에서 4 방향 모두가 될 수 있습니다.
  • PORTRAIT — 세로 방향, 특정 Android 장치에서 반전 세로가 될 수도 있습니다.
  • PORTRAIT_UP — 업사이드 초상화 만 해당.
  • PORTRAIT_DOWN — 거꾸로 된 세로 만.
  • LANDSCAPE — 모든 가로 방향.
  • LANDSCAPE_LEFT — 왼쪽 가로 만.
  • LANDSCAPE_RIGHT — 오른쪽 풍경 만.

회전 감지 :

둘 이상의 방향을 허용 change하면 Dimensions객체 의 이벤트를 수신하여 변경 사항을 감지 할 수 있습니다 .

Dimensions.addEventListener('change', (dimensions) => {
  // you get:
  //  dimensions.window.width
  //  dimensions.window.height
  //  dimensions.screen.width
  //  dimensions.screen.height
});

또는 다음 Dimensions.get('window')Dimensions.get('screen')같이 언제든지 치수를 얻을 수 있습니다 .

const dim = Dimensions.get('window');
// you get:
//  dim.width
//  dim.height

또는:

const dim = Dimensions.get('screen');
// you get:
//  dim.width
//  dim.height

당신이 이벤트를 수신 할 때 당신은 모두를 얻을 수 windowscreen다르게 액세스 왜 같은 시간에 그 그래서.

선적 서류 비치:

자세한 내용은 다음을 참조하십시오.


2
나는 장치와 재발에 엑스포를 폐쇄 작품 후
브랜든 소렌 Culley

그것을 분리하는 방법이 있습니까, Ipad처럼 가로 및 Iphone 전용 세로 허용?
7urkm3n

이것은 제 경우에 작동하는 솔루션입니다. 내 메인 뷰는 전면 광고를 닫은 후 180도 회전합니다. 그래서 하드 코딩 된 Expo.ScreenOrientation.allowAsync (Expo.ScreenOrientation.Orientation.LANDSCAPE_LEFT);
Hermann Schwarz

15

Answer for disable rotation in React Native.

For Android :

Androidmenifest.xml 파일로 이동하여 한 줄 추가 : android : screenOrientation = "portrait"

         <activity
            android:name=".MainActivity"

            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
          </activity>

For IOS :

XCODE에서 회전 모드를 확인하거나 선택 취소하면됩니다.

여기에 이미지 설명 입력


2
iOS와 Android를 모두 포함하는 2020 년 베스트 답변
raulicious

3

Expo를 사용하는 경우 다음 코드로 간단히 수행 할 수 있습니다.

Expo.ScreenOrientation.allow(Expo.ScreenOrientation.Orientation.PORTRAIT);

렌더링하기 전에 App.js에 넣으십시오.

모든 옵션 :

ALL ALL_BUT_UPSIDE_DOWN PORTRAIT PORTRAIT_UP PORTRAIT_DOWN LANDSCAPE LANDSCAPE_LEFT LANDSCAPE_RIGHT


2

Android의 경우 AndroidManifest.xml 파일을 편집해야합니다. 세로 모드로 잠 그려는 각 활동에 다음 행을 추가하십시오.

android : screenOrientation = "portrait"

따라서 전체 예제는 다음과 같습니다.

 <application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:allowBackup="false"
  android:theme="@style/AppTheme">

  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize"
    android:screenOrientation="portrait">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>

  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>

2

Android의 경우 : 매니페스트 파일에 다음을 입력합니다.

xmlns:tools="http://schemas.android.com/tools"

그런 다음 애플리케이션 태그 안에 다음을 입력합니다.

tools:ignore="LockedOrientationActivity"

그리고 모든 활동 세트에서 :

android:screenOrientation="portrait"

1

ios ipad orientaion 문제에 이것을 사용하십시오 plist 파일 https://www.reddit.com/r/reactnative/comments/7vkrfp/disabling_screen_rotate_in_react_native_both/

IOS :

<key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> </array>

1
솔루션에 대한 링크는 환영하지만 답변이없는 경우 유용한 지 확인하십시오 . 링크 주변에 컨텍스트를 추가 하여 동료 사용자가 그것이 무엇인지, 왜 존재하는지 알 수 있도록 한 다음 페이지에서 가장 관련성이 높은 부분을 인용하십시오. 대상 페이지를 사용할 수없는 경우 다시 연결합니다. 링크에 불과한 답변은 삭제 될 수 있습니다.
이중 경고음


-3

RN expo 프로젝트를 사용 중이고 앱에 react-navigation이 포함되어 있다면 다음 코드에 대한 탐색을 설정하는 것이 도움이되었습니다.

const AppNavigator = createStackNavigator(
{
    Page1: { screen: Page1}
},
{
    portraitOnlyMode: true
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.