重新加载时 UICollectionView 闪烁问题

问题描述

我正在开发一个应用程序,其中用户单击菜单项,tableView 应根据所选项目滚动。

但问题是 collectionView 在重新加载时会轻弹一点。

这里是可见部分。

func tableView(_ tableView: UITableView,willdisplay cell: UITableViewCell,forRowAt indexPath: IndexPath) {
if let firstVisibleIndexPath = self.tblRestaurantFeed.indexPathsForVisibleRows?[0]{
    self.tableViewVisibleSection = firstVisibleIndexPath.section
}}

当变量更新时,我正在重新加载 collectionview 并使用滚动到项目

var tableViewVisibleSection:Int = 0{
didSet{
        UIView.animate(withDuration: 0.15,animations: {
            self.collectionView.reloadData()
        })
        let visibleIndexPaths = collectionView.indexPathsForVisibleItems
        let itemIndex = IndexPath(item: self.selectedTag,section: 0)
        if(!visibleIndexPaths.contains(itemIndex)){
            UIView.performWithoutAnimation {
                self.collectionView.scrollToItem(at: IndexPath(item: self.selectedTag,section: 0),at: .centeredHorizontally,animated: true)
            }
        }
}}

enter image description here

任何帮助将不胜感激。

解决方法

我认为问题在于您正在从动画块调用 .reloadData()。请尝试下面的代码,让我知道它是否有效。

var tableViewVisibleSection: Int = 0 {
didSet {
        let visibleIndexPaths = collectionView.indexPathsForVisibleItems
        let itemIndex = IndexPath(item: self.selectedTag,section: 0)
        if(!visibleIndexPaths.contains(itemIndex)){
                self.collectionView.scrollToItem(at: IndexPath(item: self.selectedTag,section: 0),at: .centeredHorizontally,animated: false)
        }
}}
,

试试下面的一个。

var currentMenu: Int = 0

override func viewDidLoad() {
        ...
        
        collectionView.selectItem(at: IndexPath(item: currentMenu,animated: true,scrollPosition: [])
}

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
        currentMenu = indexPath.row
        tableView.scrollToRow(at: IndexPath(item: 0,section: currentMenu),at: .top,animated: true)
        collectionView.selectItem(at: indexPath,scrollPosition: .centeredHorizontally)
}

extension ViewController: UITableViewDelegate,UITableViewDataSource {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let indexPath = tableView.indexPathsForVisibleRows?.first,abs(indexPath.section - currentMenu) == 1,scrollView.isDragging else { return }
        currentMenu = indexPath.section
        collectionView.selectItem(at: IndexPath(item: currentMenu,scrollPosition: .centeredHorizontally)
    }
}