根据indexPath.section和indexPath.row

时间:2018-08-05 06:48:21

标签: ios swift uitableview

这些是我的结构:

struct Category{
    var category_name = String()
    var items = [Item]()
}

struct Item{
    var rows = [Row]()
}

struct Row{
    var size: Int
}

我有一个菜单对象,它是一个类别数组:

var菜单= [类别]

我填充菜单,并具有如下结构:

-category1 // section 0, row 0
    -item1 // section 0, row 1
        -row1 // section 0, row 2
        -row2 // section 0, row 3
    -item2 // section 0, row 4
    -item3 // section 0, row 5
-category2 // section 1, row 0
    -item1 // section 1, row 1
    -item2 // section 1, row 2
        -row1 // section 1, row 3
        -row2 // section 1, row 4
        -row3 // section 1, row 5
    -item3 // section 1, row 6
        -row1 // section 1, row 7

我想根据本节中的索引,用适合于结构中行类型的单元格填充UITableView

因此在上面的示例中,第0节第0行= category1。因此,我应该返回适​​合类别标题的单元格。第1行第5行= item2-> row3,因此我应该返回一个子行单元格。

行0始终等于类别单元格,但是对于给定的部分索引和行索引,如何确定结构中的单元格类型?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0{ // category cell type
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell_category") else {return UITableViewCell()}
        cell.textLabel?.text = menu[indexPath.section].category_name
        return cell
    }else{// item cell type or subrow
        // based on indexPath.section and indexPath.row, 
        // should we return an item cell or a subrow cell?
        if ( ??? ){ // item cell type
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell_item") else {return UITableViewCell()}
            return cell
        }else{ // subrow cell type
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell_subrow") else {return UITableViewCell()}
            return cell
        }
    }

这些是我对以上示例的期望值:

indexPath.section = 0
indexPath.row = 0
return cell type = cell_category

indexPath.section = 0
indexPath.row = 1
return cell type = cell_item

indexPath.section = 0
indexPath.row = 2
return cell type = cell_subrow

numberOfRowsInSection返回正确的行数。

那我该如何确定要返回哪种类型的单元格?

我认为我需要遍历所有项目并保持一个计数器,但我不知道这样做的合乎逻辑的方法。

1 个答案:

答案 0 :(得分:1)

这就是我的头顶。遍历数组,并标识在每个索引路径中将存储的单元格。假设考虑到此示例,我们有一个枚举。

enum cellType {
    case category
    case item
    case row
}

现在,您将构建一个具有每个部分单元格类型的数组。

var cells: [cellType] = []
for category in menu {
     cells.append(.category)
     if !category.items.isEmpty {
          cells.append(.item)
          for item in items {
              if !category.items.rows.isEmpty {
                  for row in category.items.rows {
                       cells.append(.row)
                  }
              }
          }
     }
}

现在使用cells数组查找要出队的单元格类型。

这是一个非常丑陋的实现,但它应该可以工作。或者至少您会知道如何开始。