【问题标题】:TableView: is it possible to Delete existing rows and insert new rows without reloading tableview or section?TableView:是否可以在不重新加载 tableview 或部分的情况下删除现有行并插入新行?
【发布时间】:2021-07-18 10:28:09
【问题描述】:

我有一个类别列表(部分标题中的CollectionView),我试图在部分行中显示数据而不重新加载部分标题。使用以下代码,

  • 如果 rows(已经加载的单元格) = post.count(要显示的新帖子) 就可以了
  • 如果行 > post.count 有效
  • 但是如果 rows
           var newIndexPaths = [IndexPath]()
           var rows = 0
           rows = tableView.numberOfRows(inSection: 1)
           self.tableView.beginUpdates()
           if rows > posts.count {
               print("rows is greater")
               for row in 0...rows {
                   if rows <= posts.count {
                       break
                   }else{
                       tableView.deleteRows(at: [IndexPath(item: row, section: 1)], with: .none)
                       rows -= 1
                   }
               }
           } else if posts.count > rows {
               print("post is greater")
               for post in 0...posts.count{
                   if post < rows {
                       newIndexPaths.append(IndexPath(row: post, section: 1))
                   }
               }
               self.tableView.insertRows(at: newIndexPaths, with: .none)
           } else {
        for row in 0...posts.count - 1 {
                   newIndexPaths.append(IndexPath(row: row, section: 1))
                   break
               }   
           }
           self.tableView.reloadRows(at: newIndexPaths, with: .none)
           self.tableView.endUpdates() ```
    

【问题讨论】:

    标签: swift uitableview


    【解决方案1】:

    是的,但您必须保持数据源数组和表视图同步。

    如果posts代表section 1的数据源数组可以插入一行

    let insertionIndex = 0
    posts.insert(newItem, at: insertionIndex)
    tableView.insertRows(at: [IndexPath(row: insertionIndex, section: 1)], with: .automatic)
    

    或删除一行

    let indexToDelete = 5
    posts.remove(at: indexToDelete)
    tableView.deleteRows(at: [IndexPath(row: indexToDelete, section: 1)], with: .fade)
    

    在这两种情况下,cellForRowAt没有被调用。

    重要的是您首先 insert/remove 将项目放入/从数据源中取出,然后调用insert/deleteRows


    这同样适用于多行。例如,您可以删除第 1 节中的所有项目

    let indexPaths : [IndexPath] = posts.indices.map{[1, $0]}
    posts.removeAll()
    tableView.deleteRows(at: indexPaths, with: .fade).
    

    在我的所有示例中,都不需要 begin-/endUpdates,因为它是一个插入/删除操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 2017-12-17
      相关资源
      最近更新 更多