【问题标题】:Swift remove element dictionary and reload tableview快速删除元素字典并重新加载表格视图
【发布时间】:2018-09-26 16:43:03
【问题描述】:

我在 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()

但是,删除行重载表时,行数不对,出现问题:

更新后现有节中包含的行数 (1) 必须等于更新前该节中包含的行数 (1),加上或减去从该节中插入或删除的行数(0 插入,1 删除)加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

【问题讨论】:

  • 这令人困惑。您显示两个属性 productSortArrayproductArray。但是你的numberOfRowsInSection 是基于productSortArraydateArray。最后,当您删除一行时更新productArray。这些都不匹配。
  • 可能不相关但从不insertRows/deleteRows之后立即致电reloadData()。你摆脱了动画,insertRows/deleteRows 确实更新了 UI。
  • dateArray 是日期数组:(
  • 在这种情况下如何删除元素字典?谢谢兄弟。
  • 您可能必须删除 productSortArray[dateArray[indexPath.section]]!!.remove(at: indexPath.row)。我强烈建议为此设计使用class(带有引用语义)。

标签: swift uitableview


【解决方案1】:

如果您创建实际代表您的数据的对象,您会发现它比处理数组和字典要容易得多……

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多