点击UICollectionView外部按钮修改数组后,UICollectionView不刷新如何解决
问题解决方案
修复现有代码错误
你当前代码的cellForItemAt数据源方法中,两次调用myCollectionView.reloadItems(at: [indexPath])属于错误写法,会触发无限循环刷新,必须全部删除,修改后的数据源扩展代码如下:
extension myViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return charList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCollectionViewCell cell.myImage.image = UIImage(named: charList[indexPath.row]) return cell } }
正确放置刷新方法
你只需要在修改数据源charList的逻辑后调用刷新即可,也就是在按钮点击方法keyNote中,删除charList首元素后添加刷新代码,修改后的点击方法如下:
@IBAction func keyNote(_ sender: UIButton) { // 先加非空判断避免数组为空时崩溃 guard !charList.isEmpty, sender.currentTitle == charList[0] else { return } charList.removeFirst() print("Correct!") playSound(sound: sender.currentTitle!) // 此处调用集合视图全量刷新 myCollectionView.reloadData() }
可选优化:丝滑局部刷新
如果不需要全量刷新整个列表,可以用局部删除动画替代reloadData(),交互体验更好:
// 替换上面的myCollectionView.reloadData()即可 myCollectionView.performBatchUpdates({ myCollectionView.deleteItems(at: [IndexPath(row: 0, section: 0)]) }, completion: nil)
内容的提问来源于stack exchange,提问作者Divya Gahlot
相关产品推荐
相关产品推荐

