android 和 iOS 都有在全局設置中固定屏幕方向的辦法髓绽,但這樣不是特別理想妆绞,因為項目中株茶,在不同頁面可能會需要橫屏或豎屏,此時就可以使用 react-native-orientation图焰,這個擴展可以動態(tài)的鎖定/解鎖屏幕方向僵闯,或設置為指定的方向。
安裝方式
yarn add react-native-orientation
安裝完之后二選一 (這個是 rn 安裝原生組件的通用命令)
- rn 6.0 之前的執(zhí)行
react-native link react-native-orientation
- rn 6.0 之后執(zhí)行
cd ios && pod install && cd ..
然后繼續(xù)
android 打開 android/app/src/main/java/com/[project]/MainActivity.java
...
// for react-native-orientation
import android.content.Intent;
import android.content.res.Configuration;
public class MainActivity extends ReactActivity {
...
// for react-native-orientation
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = new Intent("onConfigurationChanged");
intent.putExtra("newConfig", newConfig);
this.sendBroadcast(intent);
}
...
}
iOS 打開 ios/[project]/AppDelegate.m
// for react-native-orientation
#import "Orientation.h"
@implementation AppDelegate
...
// for react-native-orientation
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return [Orientation getOrientation];
}
...
安裝完事
使用方法藤滥,可直接前往 項目主頁 查看鳖粟,非常簡單(其實上面的步驟在項目主頁中也有),這里說一個項目主頁沒提到的
在使用了如 lockToPortrait()
方法鎖定屏幕方向后拙绊,由 addOrientationListener
添加的監(jiān)聽函數(shù)有不同
1向图、android 上將不會再觸發(fā)泳秀,直到調用 unlockAllOrientations()
解除鎖定
2、iOS 則不然榄攀,無論屏幕鎖定與否嗜傅,都會觸發(fā)