ReactNative和iOS原生组件的混合编程

作者: uniapp | 来源:发表于2017-07-04 15:06 被阅读203次

    这次项目改版的技术重点,是集成RN,用RN实现页面的一部分,便于对运营的改变做出及时响应.在运营要求改变时,不需要苹果官方审核,修改js代码即可完成.

    混合编程实例

    上图中的页面,下面是基本的UITableView组件.头部的产品数据部分,通过js代码实现,并设置为tableHeaderView属性.
    本例中将数据保存在iOS项目中的detail.txt文件中.在js代码中,通过设置定时器,每隔2秒,就向原生组件发送一次请求数据的消息.然后通过回调函数的方式,在头部展现出请求的数据.下拉刷新UITableView时,向js组件发送刷新消息,本例中通过js中Alert组件来显示.点击上部的头部数据后,向原生组件发送跳转控制器的消息,并在新控制器中,将js传递的产品数据展示出来.具体实现步骤如下.

    通过命令

    react-native init FetchTest --version 0.44.0

    创建指定react-native版本为0.44.0的FetchTest工程项目.
    打开ios的工程,新建控制器ZDHomeTableController,并将RCTRootView设置为其tableView的tableHeaderView.添加MJRefresh,为tableView设置mj_header. .m文件如下:

    @interface ZDHomeTableController ()<RCTRootViewDelegate>
    
    @property (nonatomic, strong) RCTRootView *rootView;
    
    @end
    
    @implementation ZDHomeTableController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
      self.tableView.tableFooterView = [UIView new];
      self.tableView.tableHeaderView = self.rootView;
      self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    }
    
    - (void)loadData{
      [[SendToRN allocWithZone:nil] refreshWithDict:@{@"value":@"refresh"}];
      [self.tableView.mj_header endRefreshing];
    }
    
    #pragma mark - Table view data source
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return 10;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
      if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
      }
      cell.textLabel.text = [NSString stringWithFormat:@"section = %zd, row = %zd",indexPath.section, indexPath.row];
        return cell;
    }
    
    #pragma mark - RCTRootViewDelegate
    - (void)rootViewDidChangeIntrinsicSize:(RCTRootView *)rootView{
      CGRect frame = rootView.frame;
      CGSize intrinsicSize = rootView.intrinsicContentSize;
      frame.size = intrinsicSize;
      rootView.frame = frame;
      [self.tableView reloadData];
    }
    - (RCTRootView *)rootView{
      if (!_rootView) {
        NSURL *jsCodeLocation;
        
        jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
        RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"FetchTest" initialProperties:nil launchOptions:nil];
        rootView.sizeFlexibility = RCTRootViewSizeFlexibilityWidthAndHeight;
        rootView.frame = CGRectMake(0, 0, ScreenSize.width, 0);
        rootView.delegate = self;
        _rootView = rootView;
      }
      return _rootView;
    }
    
    @end
    

    其中设置rootView的代理为ZDHomeTableController后,在其代理方法rootViewDidChangeIntrinsicSize中,能够通过intrinsicContentSize属性得到请求的js控件高度.在此更新tableView后,tableHeaderView的高度会调整到js代码中设定的大小.
    loadData中通过SendToRN向js发送刷新的消息.根据官方文档可以实现.

    + (id)allocWithZone:(NSZone *)zone {
      static SendToRN *sharedInstance = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
        sharedInstance = [super allocWithZone:zone];
      });
      return sharedInstance;
    }
    
    RCT_EXPORT_MODULE();
    - (NSArray<NSString *> *)supportedEvents
    {
      return @[@"RefreshEvent"];
    }
    - (void)refreshWithDict:(NSDictionary *)dict {
      [self sendEventWithName:@"RefreshEvent" body:dict];
    }
    

    注意:allocWithZone方法是必须按照以上方式重写,否者会出现以下错误:
    Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bridge is not set. This is probably because you've explicitly synthesized the bridge in SendToRN, even though it's inherited from RCTEventEmitter.'

    修改AppDelegate.m文件中的默认实现.为项目添加UINavigationController并将ZDHomeTableController设置为其根控制器.

    ZDHomeTableController *homeController = [ZDHomeTableController new];
      UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:homeController];
      nav.navigationBar.translucent = false;
      nav.navigationBar.barTintColor = [UIColor colorWithWhite:0.5 alpha:0.5];
      self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
      self.window.rootViewController = nav;
      [self.window makeKeyAndVisible];
      return YES;
    

    添加LoadHttp类用于接收js的网络请求. .m实现如下:

    #import "LoadHttp.h"
    
    @implementation LoadHttp
    
    RCT_EXPORT_MODULE();
    
    RCT_EXPORT_METHOD(loadData:(RCTResponseSenderBlock)callback){
      
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"detail.txt" ofType:nil]];
        //将字典包装成数组的形式传递
        callback(@[dict]);
      });
    }
    
    @end
    

    添加Navigate类用于接受点击js头部产品组件的事件,用于页面的跳转. .m实现:

    #import "Navigate.h"
    #import <UIKit/UIKit.h>
    #import "ZDSecondTableController.h"
    
    @implementation Navigate
    RCT_EXPORT_MODULE()
    
    RCT_EXPORT_METHOD(push:(NSDictionary *)dict){
      
      NSLog(@"%@", dict);
      dispatch_async(dispatch_get_main_queue(), ^{
        ZDSecondTableController *secTC = [ZDSecondTableController new];
        secTC.dict = dict;
        [[self getNavigation] pushViewController:secTC animated:true];
      });
    }
    
    - (UINavigationController *)getNavigation{
      UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
      return nav;
    }
    @end
    

    其中的ZDSecondTableController类用于跳转后,展示js传递的数据.

    下面添加js代码和文件.在index.ios.js文件中编辑具体的js代码.

    import React, { Component } from 'react';
    import {
        AppRegistry,
        StyleSheet,
        Text,
        View,
        Dimensions,
        FlatList,
        NativeModules,
        NativeEventEmitter,
        Alert,
    } from 'react-native';
    
    import FlatItem from './FlatItem';
    
    export default class FetchTest extends Component {
        constructor(props) {
            super(props);
            this.state = {
                data: []
            }
    
            const { SendToRN } = NativeModules;
    
            const SendToRNEmitter = new NativeEventEmitter(SendToRN);
    
            const subscription = SendToRNEmitter.addListener(
                'RefreshEvent',
                (dict) => {
                    alert(dict.value);
                }
            );
        }
      componentDidMount() {
          this.loadData();
          this.timer = setInterval(() => {
              // console.log("aaaaaa");
              this.loadData();
          }, 2000);
    
      }
    
        componentWillUnmount() {
            this.timer && clearInterval(this.timer);
            subscription.remove();
        }
    
      Item = ({item}) => {
        return(
          <FlatItem item={item}/>
        );
      }
    
      loadData = () => {
          this.setState({
              data:[]
          });
          var LoadHttp = NativeModules.LoadHttp;
          LoadHttp.loadData((response) => {
              // console.log("****" + response);
              // console.log("****" + response.success);
              if (response.success == 1){
                  //请求成功
                  this.setState({data: response.value});
              }else {
                  //网络请求失败
                  Alert.alert("请求失败");
              }
    
          });
      }
      render() {
        return (
            <View>
                <View style={styles.containerView}>
                    <FlatList style={styles.topFlat}
                              data={this.state.data}
                              renderItem={this.Item}
                              horizontal={true}
                              keyExtractor={(item, index) => item.code}
                              showsHorizontalScrollIndicator={false}
                              ItemSeparatorComponent = {SeparatorComponent}
                              showsVerticalScrollIndicator={false}
                    />
                </View>
    
            </View>
        );
      }
    }
    class SeparatorComponent extends Component {
        render() {
            return (
                <View style={styles.separatorComponent}/>
            );
        }
    }
    const {ScreenWidth, ScreenHeight} = Dimensions.get('window');
    
    const styles = StyleSheet.create({
      containerView: {
        height: 90,
        width:ScreenWidth,
        backgroundColor:'azure',
      },
      topFlat: {
        height: 90,
        width:ScreenWidth,
      },
        separatorComponent:{
            backgroundColor:'aliceblue',
            width:2,
            height:90,
        }
    });
    AppRegistry.registerComponent('FetchTest', () => FetchTest);
    

    添加FlatItem.js文件,用于显示用于FlatList的模块FlatItem.

    import React, {Component} from 'react';
    import {View,
        Text,
        StyleSheet,
        Dimensions,
        TouchableOpacity,
        NativeModules,
    } from 'react-native';
    import {ScreenWidth, ScreenHeight} from './ScreenUnit';
    
    
    export default class FlatItem extends Component {
    
        click = () => {
            let Navigate = NativeModules.Navigate;
            Navigate.push(this.props.item);
        }
    
        dealIncreasePoint = (item) => {
            let point = item.last - item.lastclose;
            let pointPercent = (item.last - item.lastclose) * 100 / item.lastclose;
            let pointStr;
            let pointPercentStr;
            let str;
            if (point > 0){
                currentColor = upperColor;
                //金,保留2位
                if(item.code.toString() == "LLG") {
                    pointStr = '+' + point.toFixed(2);
                    pointPercentStr = '+' + pointPercent.toFixed(2) + '%';
                }else if(item.code.toString() == "LLS"){
                    //银,保留3位
                    pointStr = '+' + point.toFixed(3);
                    pointPercentStr = '+' + pointPercent.toFixed(3) + '%';
                }else {
                    //美元指数,保留4位
                    pointStr = '+' + point.toFixed(4);
                    pointPercentStr = '+' + pointPercent.toFixed(4) + '%';
                }
    
            }else if(point < 0){
                currentColor = lowerColor;
                //金,保留2位
                if(item.code.toString() == "LLG") {
                    pointStr = point.toFixed(2);
                    pointPercentStr = pointPercent.toFixed(2) + '%';
                }else if(item.code.toString() == "LLS"){
                    //银,保留3位
                    pointStr = point.toFixed(3);
                    pointPercentStr = pointPercent.toFixed(3) + '%';
                }else {
                    //美元指数,保留4位
                    pointStr = point.toFixed(4);
                    pointPercentStr = pointPercent.toFixed(4) + '%';
                }
            }else {
                currentColor = item.lastColor;
            }
            item.lasColor = currentColor;
    
            return {pointString: pointStr, percentString: pointPercentStr};
        }
    
        dealBottomColor = (item) => {
            let point = item.last - item.lastclose;
            if (point > 0) {
                currentColor = upperColor;
            }else if(point < 0) {
                currentColor = lowerColor;
            }else {
                currentColor = item.lastColor;
            }
            item.lasColor = currentColor;
            return currentColor;
        }
        constructor(props){
            super(props);
    
        }
        render(){
            return(
                <TouchableOpacity onPress={this.click}>
                    <View style={styles.item}>
                        <Text>
                            {this.props.item.name}
                        </Text>
                        <Text style={{color:this.dealBottomColor(this.props.item), marginTop: 5}}>
                            {this.props.item.last}
                        </Text>
                        <View flexDirection="row">
                            <Text style= {{color:this.dealBottomColor(this.props.item), padding:5}}>
                                {this.dealIncreasePoint(this.props.item).pointString}
                            </Text>
                            <Text style= {{color:this.dealBottomColor(this.props.item), padding:5}}>
                                {this.dealIncreasePoint(this.props.item).percentString}
                            </Text>
                        </View>
                    </View>
                </TouchableOpacity>
    
            );
        };
    }
    
    let upperColor = '#F56262';
    let lowerColor = '#00B876';
    let currentColor;
    const styles = StyleSheet.create({
        item: {width: ScreenWidth / 3.0, height: 90,
            alignItems:'center',justifyContent:'center'},
    });
    

    总结
    本例中在iOS项目中,实现js和原生组件的混合编程.通过设置UITabelView的tableHeaderView将js组件用于原生项目.其中实现了js组件调用原生中请求数据和跳转页面的方法,以及原生请求数据后的回调和原生向js组件发送刷新消息.对遇到iOS项目混合编码的人,可以作为详细参考.
    详细代码请点击:Demo

    喜欢和关注都是对我的鼓励和支持~

    相关文章

      网友评论

      本文标题:ReactNative和iOS原生组件的混合编程

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