代码之家  ›  专栏  ›  技术社区  ›  TruMan1

是否调整CollectionView.ScrollToItem以考虑插入?

  •  8
  • TruMan1  · 技术社区  · 7 年前

    我有时会这样滚动到一个单元格的左边:

    CollectionView.ScrollToItem(
    位于:indexpath(行:5,节:0),
    位于:.左,//TODO:左忽略插入
    动画:真
    )
    

    这是它在ScrollToItemImplemented:之前开始的方式。

    但是,当我尝试使用滚动到项目时,它将单元格粘贴到边缘,而不考虑插入:

    是否有一种简单的方法来修复collectionview.scrollotoitem以适应插入?

    这就是以前的情况scrollToItem实施时间:

    enter image description here

    但是,当我尝试使用滚动到项目时,它将单元格粘贴到边缘,而不考虑插入:

    enter image description here

    有简单的方法吗collectionView.scrollToItem为了容纳插页?

    3 回复  |  直到 7 年前
        1
  •  5
  •   BangOperator    7 年前

       /**
         Assumptions:
         1. Your collection view scrolls horizontally
         2. You are using UICollectionViewFlowLayout to layout you collection view
    
         @param indexPath IndexPath to scroll to
         @param animated Toggle animations
         */
        - (void)scrollToIndexPathPreservingLeftInset:(NSIndexPath *)indexPath animated:(BOOL)animated {
            UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
            CGFloat sectionLeftInset = layout.sectionInset.left;
            UICollectionViewLayoutAttributes *attri = [layout layoutAttributesForItemAtIndexPath:indexPath];
            [collectionView setContentOffset:CGPointMake(attri.frame.origin.x - sectionLeftInset, 0) animated:animated];
        }
    

    Swift(未经语法验证)

    func scroll(toIndexPathPreservingLeftInset indexPath: IndexPath, animated: Bool) {
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        let sectionLeftInset = layout.sectionInset.left
        var attri = layout.layoutAttributesForItem(at: aPath)
        collectionView.setContentOffset(CGPoint(x: (attri?.frame.origin.x - sectionLeftInset), y: 0), animated: animated)
    }
    

    Sample gif

        2
  •  9
  •   Paweł Zgoda-Ferchmin    7 年前

    collectionView.scrollToItem collectionView.contentInset 而不是 layout.sectionInset

        3
  •  2
  •   manyrdz    7 年前

    let cell = collectionView.cellForItem(at: indexPath)!
    collectionView.scrollRectToVisible(cell.frame, animated: true)
    

    因为这是我们正在处理的一个帧,所以您可以对该帧微调一些所需的偏移量。