【问题标题】:Add additional rows in TableView在 TableView 中添加其他行
【发布时间】:2016-10-22 15:15:36
【问题描述】:

我使用 Swift 3。 我有 7 行的 UITableView:

override func viewDidLoad() {
        super.viewDidLoad()        
        self.tableView.delegate = self
        self.tableView.dataSource = self        
}

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
    {        
        return 7
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    if (IndexPath.row == 6)
    {
        tableView.beginUpdates()
        var index = IndexPath(row: 7, section: 0)
        tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)                    
        tableView.endUpdates()
    }
}

当我滚动到表格中的最后一个单元格时,我想添加其他单元格。 但是我收到了这个错误:

无效更新:第 0 节中的行数无效。 更新 (7) 后包含在现有节中的行必须是 等于该节之前包含的行数 update (7),加上或减去插入或删除的行数 该部分(插入 1 个,删除 0 个)并加上或减去数量 移入或移出该部分的行(0 移入,0 移出)。

【问题讨论】:

    标签: ios swift scroll tableview cell


    【解决方案1】:

    当你从 tableView 插入或删除任何行时,你应该更新你的数据源,以便对象的数量保持等于 tableView 中的行数

    func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {        
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (IndexPath.row == 6) {
            tableView.beginUpdates()
            var index = IndexPath(row: 7, section: 0)
            let newObject = // create new model object here
            dataSource.insert(newObject, at: 7)
            tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)                    
            tableView.endUpdates()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多