我在 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/