swift - 从平仓确定真实指数
问题描述
这些是我的结构:
struct Category{
var category_name = String()
var items = [Item]()
}
struct Item{
var rows = [Row]()
}
struct Row{
var size: Int
}
我有一个菜单对象,它是一个类别数组。每个类别都是一个项目数组。每个 Item 是一个 Row 数组。
var menu = [
Category(category_name: "category1", items: [Item(rows: [Row(size: 1), Row(size: 1)]), Item(), Item()]),
Category(category_name: "category2", items: [Item(), Item(rows: [Row(size: 1), Row(size: 1), Row(size: 1)]), Item(rows: [Row(size: 1)])])
]
我填充菜单,并具有如下结构:
-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
给定一个部分和行(平面位置),我需要确定:
- 行类型(
Category
、Item
或Row
) - 如果行类型是
Item
orRow
,则该项的索引 - 如果行类型为
Row
,则行的索引
以下是一些示例部分和行值以及预期结果:
**indexPath.section = 1**
**indexPath.row = 0**
Row type = category
**indexPath.section = 0**
**indexPath.row = 1**
Row type = item
Item index = 0
**indexPath.section = 0**
**indexPath.row = 3**
cell type = row
Item index = 0
Row index = 1
因此,在确定特定部分和行的结果后,我希望有一些这样的逻辑:
switch rowtype{
case category:
print("category")
case item:
print("item")
print(itemindex)
case row:
print("row")
print(itemindex)
print(rowindex)
}
我该怎么做?
解决方案
通过遍历项目和行,您应该能够确定行类型。这是我的功能(这是在 Windows 上输入的,所以我没有编译或测试它,但希望它是可以理解的)
enum RowType {
case category
case item(index: Int)
case row(itemIndex: Int, index: Int)
}
struct Category{
var category_name = String()
var items = [Item]()
func rowType(_ row: Int) -> RowType {
if row == 0 { //row 0 means we have a section selected
return RowType.category
}
var itemIndex: Int = 0
var rowCount: Int = 1
for x in items {
itemIndex += 1
if row == rowCount {
return RowType.item(index: itemIndex)
}
let lastRow = x.rows.count + rowCount
if row > lastRow {
rowCount += lastRow //not in this item, try next Item
continue
}
return RowType.row(itemIndex: itemIndex, index: row - itemIndex - 1)
}
return RowType.category //Category without items
}
}
并使用
let category = menu[indexPath.section]
let rowInfo = category.rowType(indexPath.row)
推荐阅读
- python - 更新字典的多维字典
- javascript - Leaflet / Mapbox 海上交通密度图
- python - re.sub 在一个 sub 中结合两个规则
- mongodb - 选择什么版本的mongodb?考虑过滤
- docker - 如何在 Docker for Windows 中运行的旧 docker 容器中打开新端口?
- python - 从数字中减去直到它不等于零
- html - 闪烁的svg组:悬停?
- php - System.xml 中文本字段的 Magento2 setValue()
- model - DDD End Runs,应用层调用另一个不在其正下方的
- android - 删除活动上的 Firebase 侦听器消失?