美文网首页
React native orientation 屏幕旋转监听

React native orientation 屏幕旋转监听

作者: 马六甲的笔记 | 来源:发表于2020-03-15 14:55 被阅读0次

android 和 iOS 都有在全局设置中固定屏幕方向的办法,但这样不是特别理想,因为项目中,在不同页面可能会需要横屏或竖屏,此时就可以使用 react-native-orientation,这个扩展可以动态的锁定/解锁屏幕方向,或设置为指定的方向。

安装方式

yarn add react-native-orientation

安装完之后二选一 (这个是 rn 安装原生组件的通用命令)

  • rn 6.0 之前的执行 react-native link react-native-orientation
  • rn 6.0 之后执行 cd ios && pod install && cd ..

详情可参考 官方介绍这篇文章

然后继续

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 添加的监听函数有不同

1、android 上将不会再触发,直到调用 unlockAllOrientations() 解除锁定
2、iOS 则不然,无论屏幕锁定与否,都会触发

相关文章

网友评论

      本文标题:React native orientation 屏幕旋转监听

      本文链接:https://www.haomeiwen.com/subject/sseeuctx.html