【问题标题】:How to move selected row to the top of UICollectionView如何将选定的行移动到 UICollectionView 的顶部
【发布时间】:2021-06-20 13:24:07
【问题描述】:

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

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

有人知道如何做到这一点吗? 我尝试使用自定义 UICollectionViewFlowLayout 但没有成功...

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

我想要的(灰色框是我的 CollectionView): ]2

【问题讨论】:

    标签: ios swift uicollectionview tvos uicollectionviewflowlayout


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      感谢@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, at: .top, animated: true)
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多