问题描述
在我的应用中,我有一个包含部分的表格视图(例如:运动、汽车、摩托车)。这些部分是可展开/可折叠的。如果用户点击这些部分之一,则会打开该部分下的行项目列表(示例行项目:棒球、足球)。我想要做的只是在部分(本质上是类别)内的这些行项目之间创建某种分隔符。树示例:
- 体育 (部分 - 可选择...选中时,展开显示行项目)
我不希望行dividers(类别标题)能够被选择或执行操作。我只是想让行被分开,这样它们就不会一起运行。我不希望 类别标题(例如:AMERICAN SPORTS、EUROPEAN SPORTS)可展开或折叠。只有部分(例如:体育)可以展开/折叠。单个行项目本身(例如:棒球、足球)也将在被选中时执行操作。 类别标题是唯一不可选择且没有操作的部分……它们实际上只是一个分隔符。
这是我在网上找到的关于如何在节内创建行分隔符的内容。但是,此代码中出现了一些不同的黄旗警告(我忘记了它们的名称)。我不确定代码是否 100% 正确。如果您不介意,请校对并调整评估期间需要修复的任何内容(以使其正常工作)。
我的主要问题是我需要知道如何设置他的示例代码中使用的这些变量(存储 tableView 数据)。该人表示这是一个“两级数组(部分)来表示 tableView 中的项目”。我不明白它们是如何声明的...请在代码中告诉我。
归功于@AD Progress
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 second level section headers
for rowItems: [Any] in sectionItems as? [[Any]] ?? [] {
numberOfRows += rowItems.count // For actual table rows
}
return numberOfRows
}
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 {
// Section header
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "SECTION_HEADER_CELL",for: indexPath)
cell.textLabel?.text = sectionHeaders[subsectionIndex] as? String
return cell
} else {
// Row Item
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 {
// First row for each section item is header
itemIndex = (itemIndex ?? 0) - 1
// Check if the item index is within this subsection's items
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)
}
这是获得此代码的地方:StackOverflow Article 请参考该页面了解更多详情。最后,这些用户从这里得到他们的例子:Original Article
注意:请在代码中解释你的答案。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)