美文网首页
如何为react-native提供设置屏幕方向

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

作者: 康闹闹2013 | 来源:发表于2019-05-27 18:37 被阅读0次

项目需求:

整个项目时禁止横屏的,但在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、完毕!

相关文章

网友评论

      本文标题:如何为react-native提供设置屏幕方向

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