我在一个视图控制器中有两个集合视图。顶级集合视图是空的,我希望当我选择较低集合视图中的任何项目时,此项目添加到顶部集合视图中。问题是当我选择较低集合视图中的项目应用程序崩溃时,我收到此错误:
原因:'无效更新:第0部分中的项目数无效。更新后现有部分中包含的项目数(1)必须等于更新前该部分中包含的项目数(0),加上或减去从该部分插入或删除的项目数(插入0,删除0)和加或减移入或移出该部分的项目数(0移入,0移出)。 #39;
有我的代码,怎么能解决这个问题?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
self.collectionView.collectionViewLayout = flowLayout
flowLayout.estimatedItemSize = CGSize(width: collectionView.bounds.width/3, height:32)
flowLayout.minimumLineSpacing = 2
flowLayout.minimumInteritemSpacing = 2
let flowLayout1 = self.topCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
self.topCollectionView.collectionViewLayout = flowLayout1
flowLayout1.estimatedItemSize = CGSize(width: collectionView.bounds.width/3, height:32)
flowLayout1.minimumLineSpacing = 2
flowLayout1.minimumInteritemSpacing = 2
self.collectionView.collectionViewLayout.invalidateLayout()
self.topCollectionView.collectionViewLayout.invalidateLayout()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionView {
return foodData.count
}
else {
return selectFood.count
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LCell", for: indexPath)as! CollectionLabelCell
if collectionView == self.collectionView {
cell.titleLabel.text = foodData[indexPath.row]
}
else if collectionView == self.topCollectionView {
if selectFood.count != 0 {
cell.titleLabel.text = selectFood[indexPath.row]
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.collectionView {
self.selectFood.append(foodData[indexPath.row])
self.topCollectionView.performBatchUpdates({ () -> Void in
self.topCollectionView.reloadData()
}, completion:nil)
}
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width/3, height:32)
}
答案 0 :(得分:1)
问题出在这个方法中:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.collectionView {
self.selectFood.append(foodData[indexPath.row])
self.topCollectionView.performBatchUpdates({ () -> Void in
self.topCollectionView.reloadData()
}, completion:nil)
}
}
应该是这样的:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.collectionView {
self.selectFood.append(foodData[indexPath.row])
self.topCollectionView.performBatchUpdates({ [weak self] () -> Void in
self?.topCollectionView.insertItems(at: <#T##[IndexPath]#>)
}, completion:nil)
}
}