【问题标题】:TableView cells are repeated/duplicatedTableView 单元格重复/重复
【发布时间】:2019-11-10 19:22:58
【问题描述】:

所以目前我正在为大学做一个 Swift 项目。它有一个应该有 10 个单元格的 TableView,因为我的数据数组有 10 个索引。我能够设置应用程序,除了在 10 个条目后,整个数据集重复,从第一个条目到最后一个条目...This is what the problem looks like.,一切正常。 (TableData 是保存单元格数据的数组)

override func numberOfSections(in tableView: UITableView) -> Int {
    return tableData.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableData.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath)

    let mapLocation = tableData[indexPath.row]
    cell.textLabel?.text = mapLocation.name
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    selectedLocation = tableData[indexPath.row]
    performSegue(withIdentifier: "fromTableToMap", sender: selectedLocation)
}

【问题讨论】:

  • 您可能希望返回 1 作为部分的数量。

标签: ios swift cocoa-touch


【解决方案1】:

你有

override func numberOfSections(in tableView: UITableView) -> Int {
    return tableData.count
}

替换为

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

否则,您将 10 行重复 10 次(以制作 10 个部分),从而产生 100 行。

【讨论】:

    【解决方案2】:

    使用这个。

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    

    【讨论】:

      【解决方案3】:

      您缺少UITableView 的基本概念。一个 TableView 由一个或多个部分组成,每个部分由一个或多个单元格组成。

      override func numberOfSections(in tableView: UITableView) -> Int {
          return tableData.count
      }
      
      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return tableData.count
      }
      

      这意味着您使用 10 个作为部分,每个部分有 10 行。所以它返回 10 * 10 = 100 个单元格(您可以手动计算)

      应该是

      override func numberOfSections(in tableView: UITableView) -> Int {
          return 1
      }
      
      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return tableData.count
      }
      

      现在您使用 1 作为部分,每个部分有 10 行。所以它返回 1 * 10 = 10 个单元格(您可以手动计算)

      【讨论】:

        【解决方案4】:

        只需从您的代码中删除 numberOfSections 方法,默认情况下它将占用一个部分用于 tableView。

        【讨论】:

          猜你喜欢
          • 2020-08-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          • 1970-01-01
          • 2014-11-04
          • 2017-07-01
          • 2021-12-09
          相关资源
          最近更新 更多