如何将选定行移动到 UICollectionView

问题描述

我有一个 UICollectionView 的 UICollectionView,所以每行有 1 个单元格,里面有一个 UICollectionView。

我希望所选行始终移动到我的 CollectionView 的顶部,当前所选行在 CollectionView 内居中。

有人知道如何实现这一目标吗? 我尝试使用自定义 UICollectionViewFlowLayout 但没有成功...

我下面有什么(灰色框是我的 CollectionView):

What I have below (grey box is my CollectionView)

我想要什么(灰色框是我的 CollectionView):

What I would like to have (grey box is my CollectionView)

]2

解决方法

您可以使用此滚动到所选项目:

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
     self.collectionView.scrollToItem(at: indexPath,at: .top,animated: true)
}

最后的一些项目不会进入顶部,因为它没有更多的空间来移动顶部,因此为了修复,您必须计算和设置 tableview 底部插入。

,

感谢@urvashikoladiya 的帮助

对于那些可能对解决方案感兴趣的人,我需要调度 scrollToItem 函数的调用,因为我的 UICollectionView 子单元格已经在动画,所以我必须确保动画完成,然后再要求滚动位置到顶部。

可能有更优雅的方法来做到这一点,但我还没有找到

class MyCollectionViewCell: UICollectionViewCell,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,didUpdateFocusIn context: UICollectionViewFocusUpdateContext,with coordinator: UIFocusAnimationCoordinator) {
        if let nextIndexPath = context.nextFocusedIndexPath {
        delegate?.selectedRow(cell: self)            
    }
}

class MainCollectionView: UICollectionViewController,UICollectionViewDelegateFlowLayout,CollectionViewCellDelegate {

    override func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId,for: indexPath) as! MyCollectionViewCell
        cell.delegate = self
        return cell
    }

    override func collectionView(_ collectionView: UICollectionView,canFocusItemAt indexPath: IndexPath) -> Bool {
        return false
    }

    func selectedRow(cell: MyCollectionViewCell) {
        if let indexPath = collectionView.indexPath(for: cell) {
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) {
                self.collectionView.scrollToItem(at: indexPath,animated: true)
            }
        }
    }
}