首页 > 解决方案 > 在 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)甚至没有被调用。关于哪里可能出错的任何想法?

标签: swiftmvvmuicollectionview

解决方案


我解决了。原来问题出在我的习惯UICollectionViewFlowLayout上。在其中,我调用了let numberOfItems = collectionView?.numberOfItems(inSection: section),其中section由我的数据源确定。所以我之前添加了一个保护声明,一切都很顺利:

guard let numberOfSections = collectionView?.numberOfSections,
            numberOfSections > section else { return }

你们不可能都想通了这一点,我完全没想到问题就出在这里。所以我只想把这个贴在这里,给以后可能遇到类似问题reloadData()的人——记得检查你的自定义布局!


推荐阅读