11.动态单元格的创建

来源:互联网 发布:人工智能的原理及作用 编辑:程序博客网 时间:2024/05/21 15:50

1.一种类型cell的动态单元格


  • 设置
    • 在storyoard中将tableView设置为Dynamic Prototypes(默认就是)
    • 拖一个cell(用原来的那个也可以),在cell上拖一个label命名为cell1,并将cell的Identifier命名为cell1(和之后的代码中的一样),如下图:
      这里写图片描述
  • 代码

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{//这里显示是五行的代码未粘贴
static NSString *reuseIdentifier = @"cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
return cell;
}

  • 运行效果
    这里写图片描述

  • 原理

    在缓存池中没有找到可利用的cell就会去storyboard中检测有没有为identifier为@”cell1”的cell,
    有的话就会按照这个单元格进行创建

  • 2.在storyboard中创建多种自定义cell

    • 原理

      可以在storyboard中的tableview中创建很多cell并布局不同的UI,设置不同的identifier,根据不同的indexPath设置不同的cellID,会创建出不同的cell,因为可能行高不一样,所以在tableView的代理方法中不同行返回不同的高度

    • 布局
      这里写图片描述

    • 代码

      -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      static NSString *reuseIdentifier = @"cell1";
      static NSString *reuseIdentifier2 = @"cell2";
      UITableViewCell *cell = nil;
      if (indexPath.row % 2 == 0) {
      cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
      }else{
      cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier2];
      }
      return cell;
      }

      -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
      if (indexPath.row % 2 == 0) {
      return 80;
      }else{
      return 160;
      }
      }

    • 效果
      这里写图片描述

    0 0
    原创粉丝点击