swift - 在 MVVM 中清除集合视图的正确方法
问题描述
我有一个由视图模型驱动的集合视图。当用户注销时,我想清除视图模型和集合视图。collectionView?.reload()
但是,每当我在清除视图模型时尝试调用时,程序就会崩溃: request for number of items in section 6 when there are only 0 sections in the collection view
.
class ViewModel {
private var childVMs: [ChildViewModel]()
var numberOfSections { return childVMs.count }
func numberOfItems(inSection section: Int) {
return childVMs[section].numberOfItems
}
func clear() {
childVMs.removeAll()
}
...
}
class ViewController: UICollectionViewController {
let vm = ViewModel()
func logout() {
vm.clear()
collectionView?.reloadData()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return vm.numberOfSections
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return vm.numberOfItems(inSection: section)
}
...
}
我注意到当程序崩溃时,numberOfSections(in)
按预期返回 0 并且collectionView(_, numberOfItemsInSection)
甚至没有被调用。关于哪里可能出错的任何想法?
解决方案
我解决了。原来问题出在我的习惯UICollectionViewFlowLayout
上。在其中,我调用了let numberOfItems = collectionView?.numberOfItems(inSection: section)
,其中section
由我的数据源确定。所以我之前添加了一个保护声明,一切都很顺利:
guard let numberOfSections = collectionView?.numberOfSections,
numberOfSections > section else { return }
你们不可能都想通了这一点,我完全没想到问题就出在这里。所以我只想把这个贴在这里,给以后可能遇到类似问题reloadData()
的人——记得检查你的自定义布局!
推荐阅读
- vimeo-api - 我想在 android studio 中使用 vimeo API 播放 vimeo 视频
- python - 查找不匹配模式的效率
- javascript - 如何迭代这个例子
- logic - Ramda 文档样式名称
- scala - 如何将路径列表传递给 spark.read.load?
- javascript - 如何使用节点热敏打印机连接到 ZPL 打印机?
- machine-learning - 为高精度计算损失函数的权重
- java - JavaFX - 在自定义节点上设置focusedProperty Listener
- rest - 将文件从 Angular 6 应用程序发送到 Spring Boot Web api“所需的请求部分‘文件’不存在”
- java - 如何将 JDK 库添加到我的应用程序?