调整collectionView.scrollToItem以考虑插入吗?

时间:2018-06-26 04:15:45

标签: ios swift uicollectionview uicollectionviewlayout

有时我会像这样滚动到单元格的左侧:

collectionView.scrollToItem(
    at: IndexPath(row: 5, section: 0),
    at: .left, // TODO: Left ignores inset
    animated: true
)

这是在scrollToItem实施之前开始的方式:

enter image description here

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

enter image description here

是否有一种简单的方法来修复collectionView.scrollToItem以适应插图?

5 个答案:

答案 0 :(得分:9)

如果您在collectionView.scrollToItem中而不是collectionView.contentInset中设置插入,则可以使用常规方法layout.sectionInset

答案 1 :(得分:5)

Objective-C

   /**
     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 :(得分:2)

由于每个单元格的框架都考虑了其部分插入,因此您也可以使用scrollRectToVisible(_:animated:)。

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

由于这是我们正在处理的框架,因此您可以微调该框架的所需偏移量。

答案 3 :(得分:2)

像这样将conentInset值设置为您的collectionView:

myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

,然后添加以下行:

 if #available(iOS 11, *) {
            self.myCollectionView.contentInsetAdjustmentBehavior =     .never
        }

然后scrolltoItem通过尊重collectionView的插图来工作。

答案 4 :(得分:1)

万一其他人偶然发现此滚动到水平集合视图的开始,在考虑部分插图的情况下,我可以通过执行以下操作(在Swift中5.2.4)。该解决方案利用了UICollectionViews是UIScrollViews的事实:

    (collectionView as UIScrollView).setContentOffset(.zero, animated: true)