react-native 实现单个页面横屏处理

前言

编程的世界里, 存在各种各样的需求创意,近期一个功能需求需要做到单个个别手机页面需要做横屏处理. 话不多说. 下面介绍一下代码实现

原生桥接

因为基于react-native开发, 尝试直接理由现有第三方库实现,例如:react-native-orientation,但是发现如果x-code里面deployment info设置不允许横屏. 这个组件好像并没有什么用处.


react-native 实现单个页面横屏处理_第1张图片
不允许横屏设置.png

实现思路就是利用原生桥接一个工具类,通过这个类调用原生组件属性去强制执行

iOS原生修改

AppDelegate.h代码片段

@property(nonatomic,assign)BOOL allowRotation;
@property(nonatomic, copy)NSString *direction;

AppDelegate.m代码片段

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
    if ([self.direction isEqualToString:@"right"]) {
        //横屏
        return UIInterfaceOrientationMaskLandscape;
    } else{
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
    }
    
}

DeviceOrientation.m全部代码

#import "DeviceOrientation.h"
#import "AppDelegate.h"

@implementation DeviceOrientation
RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(orientation: (NSString *)direction) {
  dispatch_async(dispatch_get_main_queue(), ^{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = YES;
    appDelegate.direction = direction;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
    NSNumber * number;
    if ([direction isEqualToString:@"right"]) {
      number = [NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight];
      [[UIDevice currentDevice] setValue:number forKey:@"orientation"];
    } else if ([direction isEqualToString:@"left"]) {
      number = [NSNumber numberWithInteger:UIInterfaceOrientationLandscapeLeft];
      [[UIDevice currentDevice] setValue:number forKey:@"orientation"];
    }
  });
}
@end

这是一个iOS桥接的工具类, 在js中调用即可

android原生修改

public class DeviceOrientation extends ReactContextBaseJavaModule {
    public DeviceOrientation(ReactApplicationContext reactContext) {
        super(reactContext);
    }
    @Override
    public String getName() {
        return "DeviceOrientation";
    }

    @ReactMethod
    public void orientation(String direction) {
        Activity currentActivity = getCurrentActivity();
        if(direction.equals("right")) {
            currentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        } else {
            currentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}

这是一个android桥接的工具类, 在js中调用即可. 调用名称跟iOS名称相同, 方便js中使用

js使用

新建一个deviceUtils.js文件

const { NativeModules } = require('react-native');

module.exports = NativeModules.DeviceOrientation;

在页面直接使用deviceUtils方法即可

DeviceOrientationUtils.orientation('right');

有问题或者建议的同学,欢迎留言讨论

你可能感兴趣的:(react-native 实现单个页面横屏处理)