您实际上可以做的是将 UIViewController 作为子视图添加到关键窗口视图控制器,但仍然将 UIViewController 的视图作为子视图添加到本机module视图中,因此它包含在本机module视图的框架和生命周期中,而无需在本机module视图的生命周期之外呈现 UIViewController 本身 ->
UIWindow *window = (UIWindow*)[[UIApplication sharedApplication] keyWindow];
[window.rootViewController addChildViewController:_myViewController];
_myViewController.view.frame = self.superview.frame;
[self addSubview:_myViewController.view];
[_myViewController didMoveToParentViewController:window.rootViewController];
这是完整的实现->
在你的 MyViewManager.m 添加
#import "RCTUIManager.h"
@interface MyViewManager ()
@end
@implementation MyViewManager
RCT_EXPORT_MODULE()
- (UIView*)view
{
return [[MyView alloc] init];
}
@end
并在您的 MyView.h 添加
#if __has_include("React/RCTViewManager.h")
#import "React/RCTViewManager.h"
#else
#import "RCTViewManager.h"
#endif
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
@interface MyView : UIView
@property(nonatomic, strong)UIViewController* myViewController;
@end
并在您的 MyView.m 添加
#import "MyView.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
@implementation MyView
- (instancetype)init
{
self = [super init];
return self;
}
- (void)dealloc
{
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (_myViewController != nil) {
_myViewController.view.frame = self.frame;
}
}
- (void)removeFromSuperview {
if (_myViewController != nil) {
[_myViewController willMoveToParentViewController:nil];
[_myViewController.view removeFromSuperview];
[_myViewController removeFromParentViewController];
_myViewController = nil;
[super removeFromSuperview];
}
}
-(void)addViewControllerAsSubView
{
_myViewController = [UIViewController new];
UIWindow *window = (UIWindow*)[[UIApplication sharedApplication] keyWindow];
[window.rootViewController addChildViewController:_myViewController];
_myViewController.view.frame = self.superview.frame;
[self addSubview:_myViewController.view];
[_myViewController didMoveToParentViewController:window.rootViewController];
}