为啥在将单元格插入带有静态单元格的表格视图时需要 tableView(_:indentationLevelForRowAt:)

Posted

技术标签:

【中文标题】为啥在将单元格插入带有静态单元格的表格视图时需要 tableView(_:indentationLevelForRowAt:)【英文标题】:why it needs tableView(_:indentationLevelForRowAt:) when Inserting cell into a table view with static cells为什么在将单元格插入带有静态单元格的表格视图时需要 tableView(_:indentationLevelForRowAt:) 【发布时间】:2017-07-28 17:26:53 【问题描述】:

背景

故事来自ios apprentice (Ed. 6 2016)一书的第二个例子

创建了一个包含两个部分的 UItableView。在情节提要中设计了以下内容:第 0 部分有一行填充了一个静态单元格,第 1 部分有两行填充了两个静态单元格。

要实现的目标

当点击第 1 部分的最后一行(即图 A 中的 dueDate 行)时,一个带有 UIDatePicker 的新单元格将被插入到 tableView 中(请参见图 B)

作者是如何解决问题的

在storyBoard的scene dock中添加了一个用UIDatePicker填充的UITableViewCell(请看图C),当点击dueDate行时,新的tableCell将添加到表格中

带有静态单元格的表格视图没有数据源,因此不使用“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, section: indexPath.section)

【问题讨论】:

【参考方案1】:

实现tableView(_:indentationLevelForRowAt:) 允许您以分层/树视图类型格式显示表格行。如:

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

【讨论】:

以上是关于为啥在将单元格插入带有静态单元格的表格视图时需要 tableView(_:indentationLevelForRowAt:)的主要内容,如果未能解决你的问题,请参考以下文章

如何使新插入的表格视图单元格的文本字段处于活动状态?

指定“左侧详细信息”表格视图单元格的文本

插入带有大单元格的表格单元格动画

静态单元格的内容没有出现 UITableView

带有自定义表格视图单元格的表格视图在滚动时消失

带有空单元格的表格视图