调整collectionView.scrollToItem以考虑插入?

Tru*_*an1 10 ios uicollectionview uicollectionviewlayout swift

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

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

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

在此输入图像描述

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

在此输入图像描述

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

Paw*_*min 11

collectionView.scrollToItem如果您将inset设置为collectionView.contentInset而不是,则可以使用常规方法layout.sectionInset


小智 6

将 conentInset 值设置为您的 collectionView,如下所示:

myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
Run Code Online (Sandbox Code Playgroud)

然后添加这一行:

 if #available(iOS 11, *) {
            self.myCollectionView.contentInsetAdjustmentBehavior =     .never
        }
Run Code Online (Sandbox Code Playgroud)

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


Ban*_*tor 5

目标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];
    }
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

样本gif