专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

SubTableView显示内容

  • 要显示 子分类 的数据需要记录下当前选中的 主分类, 在 CZCategoryViewController 中定义 selectedMainRow 属性,用于记录当前选中的 主分类

      @interface CZCategoryViewController () <UITableViewDataSource, UITableViewDelegate>
      @property (weak, nonatomic) IBOutlet UITableView *mainTableView;
    
      @property (weak, nonatomic) IBOutlet UITableView *subTableView;
    
      @property (nonatomic, strong) CZCategoryViewModel *categoryVM;
    
      @property (nonatomic, assign) NSUInteger selectedMainRow;
      @end
    
  • 实现 tableView 的代理方法 tableView:didSelectRowAtIndexPath:,当点击的是 mainTableViewcell 时,记录选中的 cell

      - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
          if (tableView == self.mainTableView) {
              // 记录mainTableView选中的cell
              self.selectedMainRow = indexPath.row;
    
              // 刷新subTableView的数据
              [self.subTableView reloadData];
          }
      }
    
  • tableView:numberOfRowsInSection: 方法返回 subTableViewcell 数量
      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
          // mainTableView返回分类数据的数量
          if (tableView == self.mainTableView) {
              return self.categoryVM.categories.count;
          } else {
              // 获取选中的MainTableView对应的cell的子分类数据
              CZCategoryModel *model = self.categoryVM.categories[self.selectedMainRow];
              return model.subcategories.count;
          }
      }
    
  • tableView:cellForRowAtIndexPath: 返回 subTableView 显示的内容

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
          if (tableView == self.mainTableView) {
              CZDropdownMainCell *cell = [tableView dequeueReusableCellWithIdentifier:mainCellIdentifier forIndexPath:indexPath];
    
              CZCategoryModel *model = self.categoryVM.categories[indexPath.row];
              cell.textLabel.text = model.name;
    
              // 设置图片
              cell.imageView.image = [UIImage imageNamed:model.small_icon];
              cell.imageView.highlightedImage = [UIImage imageNamed:model.small_highlighted_icon];
    
              // 设置右边箭头
              if (model.subcategories.count > 0 ) {
                  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
              } else {
                  cell.accessoryType = UITableViewCellAccessoryNone;
              }
    
              return cell;
          } else {
              CZDropdownSubCell *cell = [tableView dequeueReusableCellWithIdentifier:subCellIdentifier forIndexPath:indexPath];
    
              CZCategoryModel *model = self.categoryVM.categories[self.selectedMainRow];
    
              cell.textLabel.text = model.subcategories[indexPath.row];
    
              return cell;
          }
      }