如果有人对上述代码的Swift 4.2版本感兴趣,这里有一个。
为了拥有嵌套的部分,您需要在tableView中有几种类型的行。第一种表示第二级部分,第二种表示tableView中的标准行。假设您有一个两级数组(部分)来表示tableView中的项目。
然后,我们拥有的总部分数就是顶层部分的数量。每个顶层部分中的行数将是子部分的数量加上每个子部分中的行数。
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionItems = sections[section]
var numberOfRows: Int = sectionItems.count
for rowItems: [Any] in sectionItems as? [[Any]] ?? [] {
numberOfRows += rowItems.count
}
return numberOfRows
}
现在,您只需要考虑如何创建tableView的行。在故事板中设置两个原型,分别用于不同的重用标识符,一个用于节标题,另一个用于行项目,然后根据数据源方法中的请求索引实例化正确的原型。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var sectionItems = sections[indexPath.section]
var sectionHeaders = self.sectionHeaders[indexPath.section]
let itemAndSubsectionIndex: IndexPath? = computeItemAndSubsectionIndex(for: indexPath)
let subsectionIndex = Int(itemAndSubsectionIndex?.section ?? 0)
let itemIndex: Int? = itemAndSubsectionIndex?.row
if (itemIndex ?? 0) < 0 {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "SECTION_HEADER_CELL", for: indexPath)
cell.textLabel?.text = sectionHeaders[subsectionIndex] as? String
return cell
} else {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "ROW_CONTENT_CELL", for: indexPath)
cell.textLabel?.text = sectionItems[subsectionIndex][itemIndex ?? 0] as? String
return cell
}
}
func computeItemAndSubsectionIndex(for indexPath: IndexPath?) -> IndexPath? {
var sectionItems = sections[Int(indexPath?.section ?? 0)]
var itemIndex: Int? = indexPath?.row
var subsectionIndex: Int = 0
for i in 0..<sectionItems.count {
itemIndex = (itemIndex ?? 0) - 1
let subsectionItems = sectionItems[i] as? [Any]
if (itemIndex ?? 0) < Int(subsectionItems?.count ?? 0) {
subsectionIndex = i
break
} else {
itemIndex -= subsectionItems?.count
}
}
return IndexPath(row: itemIndex ?? 0, section: subsectionIndex)
}