文档

卡片自定义标签

本文介绍了在卡片中自定义标签的实现步骤。

  1. 客户端注册自定义标签(自定义 View)。

    1. 实现自定义标签(自定义 View)。

      继承 CCardWidget 并实现其协议方法,其中 onCreateViewupdateData 为必须实现的方法,其他方法为可选。

      #import "CustomCardView.h"
      
      @interface CustomCardView ()
      
      @property (nonatomic, strong) UILabel *titleLabel;
      
      @end
      
      @implementation CustomCardView
      
      //必须实现
      /**
       * UI 创建接口,表示当前组件要上屏的视图 UI
       *
       * @param data  map 类型,组件在卡片上声明的数据,包括样式、事件和属性,对应的 key 为DATA_KEY_STYLES、DATA_KEY_EVENTS、DATA_KEY_ATTRS;
       * @param size  View 的大小,宽高
       * @return 可用的 UIView
       */
      - (UIView *)onCreateView:(NSDictionary *)data size:(CGSize)size {
          NSLog(@"数据打印:%@", data);
          
          UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
          customView.backgroundColor = [UIColor redColor];
          
          self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, 30)];
          //数据来源是 data 提供
          self.titleLabel.text = @"A";
          [customView addSubview:self.titleLabel];
          
          return customView;
      }
      
      //必须实现
      /**
       * 组件数据更新接口
       * @param data
       */
      - (void)onUpdateData:(NSDictionary *)data {
          NSLog(@"数据打印:%@", data);
      }
      
      /**
       *  从复用池中获取的已存在控件,被使用前的数据准备。
       *  @param data 初始化数据
       *  @param size 组件复用时的大小
       */
      - (void)onReuse:(NSDictionary *)data size:(CGSize)size {
          NSLog(@"数据打印:%@", data);
          NSLog(@"Size打印:%@", size);
          
          //数据来源是 data 提供
          self.titleLabel.text = @"B";
      
      }
      
      /**
       * 组件是否支持复用;
       * 为了提高效率,扩展组件可以支持复用。例如当某个自定义的标签组件由于数据更新被移除当前视图,此时该组件如果支持复用,那么会放入复用池内,下次该组件显示时,会直接从复用池内获取;
       * @return YES:复用;NO:不复用。
       */
      - (BOOL)canReuse {
          return YES;
      }
      
      /**
       * 组件复用清理接口。如果组件支持复用(canReuse 返回 true),则组件在进入复用池后会调用
       * onRecycleAndCached 方法,表示当前组件已经离屏放入缓存内,需要清理资源。
       */
      - (void)onRecycleAndCache {
          //清理自定义 View 上的 SubView 内容
          self.titleLabel.text = @"";
      }
    2. 注册自定义标签。

      第一个参数是自定义的标签,需要与卡片侧约定好,在卡片侧会写到 <> 内。建议加上前缀,防止和动态卡片本身的标签冲突。第二个是自定义标签实现类的类名。

      CubeWidgetInfo *widgetInfo = [CubeWidgetInfo new];
      widgetInfo.tag = @"custom-widget";
      widgetInfo.className = [CustomCardView class];
          
      NSMutableArray *widgetArray = [NSMutableArray array];
      [widgetArray addObject:widgetInfo];
      [[[CubeService sharedInstance] getEngine] registerWidgets:[NSArray arrayWithArray:widgetArray]];
  2. 卡片侧调用。

    在标签中,写入自定义的标签。此处为 custom-widget,对应客户端注册的标签。

    说明

    写入的自定义标签需要和注册自定义标签步骤中的第一个参数保持一致。

    <template>
        <div class="root">
            ···
            <custom-widget></custom-widget>
                                    ···
        </div>
    </template>
  3. 将卡片打包发布到后台或者预览,即可渲染客户端自定义的 View。

  • 本页导读 (0)
文档反馈