如何为react-native提供设置屏幕方向

项目需求:

整个项目时禁止横屏的,但在RN的某个页面中,点击某个按钮,调用原生的一个接口,提供设置屏幕横屏或者竖屏的功能。

1、首先,Xcode工程中设置禁止横屏:

2、新建一个继承RCTBridgeModule的类

.h

#import

#import "React/RCTBridgeModule.h"

NS_ASSUME_NONNULL_BEGIN

@interfaceUtilManager :NSObject

@end

NS_ASSUME_NONNULL_END

.m的实现

#import "UtilManager.h"

#import "AppDelegate.h"

@implementation UtilManager

RCT_EXPORT_MODULE(UtilModule)

RCT_EXPORT_METHOD(screenSwitch)

{

  dispatch_async(dispatch_get_main_queue(), ^(){

    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {

      AppDelegate*delegate =(AppDelegate*)[UIApplicationsharedApplication].delegate;

      delegate.supportRotate=YES;

      [self orientationToPortrait:UIInterfaceOrientationLandscapeRight];

    }else{

      AppDelegate*delegate =(AppDelegate*)[UIApplicationsharedApplication].delegate;

      delegate.supportRotate=NO;

      [self orientationToPortrait:UIInterfaceOrientationPortrait];

    }

  });

}

- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {

  SEL selector = NSSelectorFromString(@"setOrientation:");

  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];

  [invocationsetSelector:selector];

  [invocationsetTarget:[UIDevice currentDevice]];

  intval = orientation;

  [invocationsetArgument:&valatIndex:2];

  [invocationinvoke];

}


3、在AppDelegate.h中,添加属性

@property (nonatomic, assign) BOOL supportRotate;


4、在AppDelegate.m中添加方法:

- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window {

  if (self.supportRotate) {

    return UIInterfaceOrientationMaskLandscapeRight;

  }

  return UIInterfaceOrientationMaskPortrait;

}

5、js中调用

import {NativeModules, Platform}from 'react-native'

NativeModules.UtilModule.screenSwitch();

6、完毕!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容