【问题标题】:Proper way to clear collection view in MVVM在 MVVM 中清除集合视图的正确方法
【发布时间】:2018-05-11 21:33:27
【问题描述】:

我有一个由视图模型驱动的集合视图。当用户注销时,我想清除视图模型和集合视图。但是,当我在清除视图模型时尝试调用 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) 甚至没有被调用。有没有想过哪里可能出错了?

【问题讨论】:

  • 这只是一个UICollectionViewController,已添加
  • 主线程上是否调用了logout()
  • 请回答 Mike Taverne 的问题。
  • 是的,说UIButton.addtarget(target: self, #selector(logout))

标签: swift mvvm uicollectionview


【解决方案1】:

因为你已经移除了所有的 ChildViewModel,childVMs 是空数组,在调用函数 numberOfItems(inSection section: Int) 之前。它使您的应用程序崩溃,因为您在空数组中获得了一个元素:childVMs[section],childVMs.count 对于空数组是安全的。

【讨论】:

    【解决方案2】:

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

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

    你们不可能都知道这一点,我完全没想到问题出在这。因此,我只想在这里发布此内容,以供将来可能遇到reloadData() 类似问题的人使用----记得检查您的自定义布局!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2020-08-22
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      相关资源
      最近更新 更多