swift - UICollectionView 中 cellForItemAt 的滚动单元格问题

标签 swift uicollectionview

编辑: 问题解决了。我遵循有关如何从 LBTA 构建 Youtube 的 Youtube 教程。

我的 homeController 包含 4 个可以水平滚动的单元格。每个单元格(还有 UICollectionViewCell)都有不同的获取方法来从 Firebase 加载数据。

我有以下用于滚动的代码:

//在我的 setupCollectionView 中

if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
    }

我还有:

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let index = Int(targetContentOffset.pointee.x / view.frame.width)
    let indexPath = IndexPath(item: index, section: 0)
    menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
    setTitleForIndex(index: index)

}

我有一个菜单栏附加到collectionView,菜单栏工作正常。但 UICollectionViewCell 却没有。

当我通过左右滚动来测试它时,索引号到处都是。例如,当我滚动到第一个单元格时,它显示 2 或 3,或者有时不显示任何内容。当我尝试向左滚动第一个单元格时,我仍然看到单元格编号发生变化。

我想问一下在我的情况下识别细胞的适当方法是什么?请提供一些示例代码。谢谢。下图显示了我目前的状态。

最佳答案

您不需要重写scrollViewWillEndDragging 方法。对于collectionViews,您正在重用单元格。因此,当您滚动到屏幕外的单元格时,将调用 collectionViewCellForItemAt 方法。我假设您一次只显示 1 个单元格。因此,当显示新单元格时,您只需根据重用的单元格更改标题即可。

// Note I only used partial code from your method
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: numberViewCellId, for: indexPath) as! ThirdViewCell 
        cell.delegate = self
        setTitleForIndex(index: indexPath.Row)
        return cell
    }

关于swift - UICollectionView 中 cellForItemAt 的滚动单元格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113085/

相关文章:

swift - 如何使用 RxSwift 运算符一次选择所有项目?

ios - 如何将数据保存到模型coredata

ios - Xcode 7.1.1 UINavigationBar 未覆盖 iPhone 6 及更高版本屏幕的整个宽度

ios - 为什么我的 UICollectionViewController 不能与两个 CollectionView 一起运行?

ios - UICollectionView for Springboard 像文件夹

ios - 添加对自定义单元格的支持后,MessageKit Collection View 不显示任何单元格

ios - swift : collectionView takes too long to display

swift - 为什么 NSNumber 不尊重语言环境 decimalSeparator

swift - 延迟单元测试

ios - 是否可以在 UICollectionView 下有一个 UITableView?