swift - 在 Swift 中插入行崩溃

标签 swift uitableview

我在 TableView 中插入单元格时遇到崩溃。我试过以下链接但不确定是什么问题

Link1 Link2 Link3还有很多

下面是我的代码

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

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = names[indexPath.row]
    return cell
}

数据源代码如下

   private var names: [String] = (50...99).map { String($0) }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.appendCells()
        }

    }

    private func appendCells() {

        names = (0...49).map { String($0) } + names
        customTableView.beginUpdates()
        let indexPat = IndexPath(row: names.count - 1, section: 0)
        customTableView.insertRows(at: [indexPat], with: .fade)
        customTableView.endUpdates()

    }

我不明白我在这里错过了什么。对不起,如果我做傻事。如果我需要解释更多,请告诉我。

我收到错误:

原因:'无效更新:第 0 部分中的行数无效。更新后现有部分中包含的行数 (100) 必须等于更新前该部分中包含的行数(50),

最佳答案

问题是您添加到数据模型的值的数量与您添加到 TableView 的行数不匹配。

行:

names = (0...49).map { String($0) } + names

向您的数据模型添加 50 个新值。

但是您随后只告诉 TableView 有一个新行。这就是错误消息中告诉您的内容。

您需要一个循环来构建包含 50 个索引路径的数组。

private func appendCells() {
    names = (0...49).map { String($0) } + names
    var paths = [IndexPath]()
    for row in 0...49 {
        let indexPath = IndexPath(row: row, section: 0)
        paths.append(indexPath)
    }
    customTableView.insertRows(at: paths, with: .fade)
}

关于swift - 在 Swift 中插入行崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102013/

相关文章:

iOS UITableViewCells 行被回收且标签不起作用

ios - 能够按字幕搜索

ios - 在 objective-c 中按顺序执行 block 代码

swift - 泛型的最终自类,在方法签名中,在 Swift 中

ios - 快速依赖注入(inject),具有两个 UIViewController 的依赖关系图,没有共同的父级

iOS swift : UIWebView has extremely big content

ios - 电影/GIF 背景 iOS 应用

ios - 在第一次加载时隐藏 UITableView 的部分

ios - 为什么我不能在表格 View 中显示我的图像?

ios - 将数组保存为核心数据中的数据的正确方法是什么?