iOS

RN调用原生的页面

公司的项目想往RN靠拢,先把一个板块转换为RN开发,这就涉及到了RN调用老的原生页面,经过研究,这样做可以很方便的调用以前的页面

Posted by yasin on May 24, 2016

暴露给RN的接口

//push方式切换页面
RCT_EXPORT_METHOD(pushTo:(NSString *)name param:(NSDictionary *)param)
{
    //要在主线程里面刷新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [NoticeMgr.Tabbar.selectedViewController pushViewController:[self getVCWithName:name andParam:param] animated:YES];
    });
}
//模态方式切换页面
RCT_EXPORT_METHOD(presentTo:(NSString *)name param:(NSDictionary *)param){
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:[self getVCWithName:name andParam:param] animated:YES completion:^{
        }];
    });
}

根据字符串获取要切换的控制器,并设置了属性

-(UIViewController *)getVCWithName:(NSString *)name andParam:(NSDictionary *)param{
    id corl = [[NSClassFromString(name) alloc]init];
    if([corl isKindOfClass:[UIViewController class]]){
        for(NSString *key in [param allKeys]){
            NSLog(@"11");
            //遍历控制器所有属性,如果有相同的才设置
            for(NSString *prop in [self getAllPropertyWithClass:corl]){
                if([key isEqualToString:prop]){
                    [corl setValue:param[prop] forKey:prop];
                    break;
                }
            }
        }
        UIViewController *cc = corl;
        cc.hidesBottomBarWhenPushed=YES;
    }
    return corl;
}

运行时获取目标页面拥有的属性

-(NSMutableArray *)getAllPropertyWithClass:(id)Class{
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([Class class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray array];
    for (int i = 0; i<count; i++)
    {
        const char* propertyName =property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    free(properties);
    return propertiesArray;
}