Swift 删除元素字典并重新加载 tableview

标签 swift uitableview

我在 CoreData 中有一个字典和产品:

var productSortArray: [Date:[Product]?] = [:]
var productArray = [Product]()

这是我的 numberOfRowsInSection:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return (productSortArray[dateArray[section]]!!.count)
}

当我删除提交编辑样式中的行时,我更新:

self.productArray.remove(at: indexPath.row)                
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.reloadData()

但是,当删除行并重新加载表时,行数不正确并且出现问题:

The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

最佳答案

如果您创建实际代表数据的对象,您会发现它更容易,而不是处理数组和字典......

struct ProductSection {
    let date: Date
    var products: [Product]
}

var sections: [ProductSection] = // Initialise this

然后

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section].products.count 
}


然后删除一行...

sections[indexPath.section].remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)

关于Swift 删除元素字典并重新加载 tableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522557/

相关文章:

swift, 发送文件到服务器

ios - OpenGL 纹理在使用 Swift 的 iOS 上不显示

arrays - Int 的 Swift 3 二维数组

ios - TableViewCell 重叠文本

arrays - 如何通过 JSON 将数组从 php 解压到 Swift 中

ios - Xcode 4.2 UITableViewCell 背景

json - 使用 Codable 在一个模型类中解码两个不同的 JSON 响应

swift/ SpriteKit : Numerical variable always returning 0

swift - UITableViewAutomaticDimension 的最小单元格高度

iphone - UISegment 根据当前位置和位置之间的距离对 TableView 进行排序