从 ReactNative rootviewcontroller 获取呈现的 Viewcontroller

iOS*_*eky 9 ios npm react-native react-native-native-module

在 React Native 项目中,我想从 iOS npm 模块访问 Presented Viewcontroller。我可以使用下面的代码访问 RN 项目的 rootviewcontroller

UIViewController *vc = [UIApplication sharedApplication].delegate.window.rootViewController;
Run Code Online (Sandbox Code Playgroud)

但我希望当前的 VC 呈现在 RootVC 之上,以便我应该能够在其之上呈现本机(iOS)UINavigationController。

注意:[UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController返回零。

Raj*_*jiv 12

我知道很久以前就有人问过这个问题,但今天我遇到了同样的问题([UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController返回nil)并且有一段时间找不到解决方案,所以我将把这个问题留在这里供仍在寻找的人使用。

React Native 源代码中有一个函数可以让你确定所呈现的视图控制器。看起来他们将其用于他们的 ActionSheetIOS 模块(请参阅这一)。要在您自己的本机模块中使用它,请添加以下内容:

// Put this near the top of the file
#import <React/RCTUtils.h>

...

// Put this where you need access to the presented view controller
UIViewController *presentedViewController = RCTPresentedViewController();
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您想在 Swift 中访问“RCTPresentedViewController”,您可以将“#import &lt;React/RCTUtils.h&gt;”行添加到“&lt;ModuleName&gt;-Bridging-Header.h”文件中。 (4认同)