【问题标题】:Indentation only for one cell缩进仅适用于一个单元格
【发布时间】:2015-04-19 10:26:31
【问题描述】:

所以这是一个 API。我有两个带有项目 ID([projects][id] - ids)和父母 ID([projects][parent][id] - projectsParentIDs)的字段。我在方法cellForRowAtIndexPath 中比较这两个字段,如下所示。到目前为止一切顺利(我认为)。如果索引为 1 的projectsParentID 与索引为 0 的id 相同,则缩进cell。但是这段代码正在缩进所有单元格。不止一个。我做错了什么?

for index in 0...self.projectsParentIDs.count-1 {
  if(ids[index] == projectsParentIDs[index]+1){
    cell.indentationLevel = 1
    cell.indentationWidth = 30
  }
}


"projects":[
    {
        "id":22,
        "name":"MND",
        "created_on":"2015-04-17T15:41:10+02:00",
        "updated_on":"2015-04-17T15:41:10+02:00"
    },
    {
        "id":23,
        "name":"MND child",
        "parent":{
            "id":22,
            "name":"MND"
    }
],
"created_on":"2015-04-18T11:28:12+02:00",
"updated_on":"2015-04-18T11:28:12+02:00"


func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {

    var indent: Int = 1

    if(indexPath.section == 1){
        for index in 0...self.projectsParentIDs.count-1 {
            if(ids[index] == projectsParentIDs[index]+1){
                indent = 1
                return indent
            }else{
                indent = 0
                return indent
            }
        }
    }
    return indent
}

【问题讨论】:

  • 这里的排序似乎很奇怪——我希望根项目排在第一位——有了这些数据,第一个项目将是一个孩子,因此会缩进,而第二个项目则不会。这是我对可能发生的事情的猜测。屏幕上显示的所有第一行都是子级。这些是唯一要分配的 tableview 单元格。当 tableview 来到第一个父级时,它会重用一个单元格-但如果项目是父级,您的代码不会将缩进重置为 0,因此它们都是缩进的。在 tv 子类上重置 prepareForReuse 中的缩进或将 if 添加到 cellForRow:

标签: ios swift alamofire swifty-json


【解决方案1】:

请使用以下UITableViewdelegate方法:

optional func tableView(_ tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int

【讨论】:

  • 这个方法我知道,但是应该怎么用呢?请参阅我编辑的问题。它仍然无法正常工作。即使我写了 indexPath.section = 1,它也会缩进 indexPath.section = 0。而且它仍在缩进所有单元格。
  • 您是使用预定义的UITableViewCellStyle 之一还是自定义的?如果自定义请检查例如that answer(在这种情况下您应该手动处理缩进)
  • 请看我编辑的问题。我添加了项目页面的屏幕截图。
  • 缩进计算代码中可能存在一些错误逻辑?尝试返回类似indexPath.section == 1 && indexPath.row == 0 的简单内容。如果按预期工作,那么您应该更详细地调试您的数组
  • 我在项目部分看到不同的缩进,看起来很有效,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多