这些是我的结构:
struct Category{
var category_name = String()
var items = [Item]()
}
struct Item{
var rows = [Row]()
}
struct Row{
var size: Int
}
我有一个菜单对象,它是一个类别数组:
var menu = [类别]
我填充菜单,并具有如下结构:
-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 部分 = 类别 1。所以我应该返回一个适合类别标题的单元格。 Section 1 row 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 返回正确的行数。
那么我如何确定要返回的单元格类型?
我想我需要遍历这些项目并保留一个计数器,但我想不出这样做的合乎逻辑的方法。
最佳答案
在我的脑海中,这就是我所拥有的。遍历数组并确定每个索引路径出现的单元格并存储它。假设考虑到这个例子,我们有一个枚举。
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)
}
}
}
}
}
现在使用单元格数组查找要出队的单元格类型。
这是一个非常丑陋的实现,但它应该可以工作。或者至少您会知道如何开始。
关于ios - 根据indexPath.section和indexPath.row判断多维结构的cell类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51692050/