首页 > 解决方案 > 如何在不重新加载所有数据的情况下将单元格添加到 tableView?

问题描述

如何将单元格(自定义)添加到 tableView?我尝试了以下方法:

  @IBAction func AddCommentButton(_ sender: Any) {
        addComment() {
             //1)
            self.tableView.beginUpdates()
            tableView.reloadRows(at: [arrayOfComments.count].indices, with: .automatic)
            self.tableView.endUpdates()
               //2)
//            let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: tableView.numberOfRows(inSection: 0)) as! commentTableViewCell
//            addTemporaryComment(cell: cell)
        }
    }

1)产量:

无法将类型“Range.Index>”(又名“Range”)的值转换为预期的参数类型“[IndexPath]”

2)使用这种方法也会产生很多错误:都是;

使用未解析的标识符“indexPath”;你的意思是“索引路径”吗?

    func addTemporaryComment(cell: commentTableViewCell) {
    do {
        let url = URL(string: (arrayOfComments[indexPath.row].user.profileImageUrlString)!)
        let imageData = try Data(contentsOf: url!)
        let image = UIImage(data: imageData)

        cell.dateOfComment.text = arrayOfComments[indexPath.row].date
        cell.commentText.text = arrayOfComments[indexPath.row].commentText
        cell.profImage.image = image
        cell.username.text = arrayOfComments[indexPath.row].user.username
    } catch {
        print(error, ": Failed in do block converting image")
    }
}

}

我什至不知道是否会起作用。

如果它们是正确的方法,我该如何解决这些问题,如果不是,我该如何让它发挥作用?

标签: iosswiftuitableview

解决方案


第一步应该是将新数据附加到表格视图用来填充数据的数组中

YourTablearray.append([labeltext])  

接下来更新表格数据以在表格末尾插入单元格

tableName.beginUpdates()
tableName.insertRowsAtIndexPaths([
NSIndexPath(forRow: YourTablearray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tableName.endUpdates()

推荐阅读