背景
故事来自 IOS apprentice (Ed. 6 2016)
这本书的第二个例子创建了一个包含两个部分的 UItableView。在 Storyboard中设计了以下内容:第 0 节有一行填充了一个静态单元格,第 1 节有两行完全填充了两个静态单元格。
实现什么
当点击第 1 部分的最后一行(即图片 A 中的 dueDate 行)时,带有 UIDatePicker 的新单元格将插入到 tableView 中(请参见图片 B)
作者是如何解决问题的
一个填充有 UIDatePicker 的 UITableViewCell 被添加到 storyBoard 的scene dock(请看图 C),当 dueDate 行被点击时,新的 tableCell 将被添加到表中
带有静态单元格的 TableView 没有数据源,因此不使用像“cellForRowAt”这样的函数。为了将此单元格插入表中,以下数据源函数已被覆盖
tableView(_:numberOfRowsInSection:)
tableView(_:cellForRowAt:)
tableView(_:heightForRowAt:)
tableView(_:indentationLevelForRowAt:)
问题
函数 tableView(_:indentationLevelForRowAt:)
真的让我很困惑!这是完整的代码
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
var newIndexPath = indexPath
if indexPath.section == 1 && indexPath.row == 2 {
newIndexPath = IndexPath(row: 0, section: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
}
问题
这个函数是什么意思?它的目的是什么?我读过 document ,但我没有得到太多信息。
当插入第三行/datePicker 单元格时 (indexPath.section == 1 && indexPath.row == 2)
为什么函数会缩进第一行 newIndexPath = IndexPath(row : 0, 部分: indexPath.section)
?
最佳答案
实现 tableView(_:indentationLevelForRowAt:)
允许您以分层/ TreeView 类型格式显示表格行。如:
Level 1
Sub-Level 1a
Sub-Level 1b
Level 2
Sub-Level 2a
Sub-sub-level 2aa
Sub-sub-level 2ab
etc...
通常,人们可能会使用:
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
if let myObj = myData[indexPath.row] as? MyObject {
return myObj.myIndentLevel
}
return 0
}
举个例子,没看书...
看起来作者决定包含 UIDatePicker
的新行 (2
) 应该与第一行具有相同的缩进级别节中的行 (0
)。如果它不是 2
行,则返回默认/当前缩进级别。
虽然,意图
var newIndexPath = indexPath
if indexPath.section == 1 && indexPath.row == 2 {
newIndexPath = IndexPath(row: 0, section: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
可能看起来更明显/更清晰
newIndexPath = IndexPath(row: 0, section: 1)
因为它已经将此限制为 section == 1
。
关于ios - 为什么它需要 tableView(_ :indentationLevelForRowAt:) when Inserting cell into a table view with static cells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45379230/