Ios 调整CopyVIEW.ScRotoTobe来考虑插图?

Ios 调整CopyVIEW.ScRotoTobe来考虑插图?,ios,swift,uicollectionview,uicollectionviewlayout,Ios,Swift,Uicollectionview,Uicollectionviewlayout,我有时会像这样滚动到单元格的左侧: collectionView.scrollToItem( at: IndexPath(row: 5, section: 0), at: .left, // TODO: Left ignores inset animated: true ) myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) 这是在scrollToIt

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

collectionView.scrollToItem(
    at: IndexPath(row: 5, section: 0),
    at: .left, // TODO: Left ignores inset
    animated: true
)
myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
这是在
scrollToItem
实现之前的开始方式:

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


是否有一种简单的方法来修复集合视图。scrollToItem以容纳插入?

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

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

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(未进行语法验证)


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

collectionView.scrollToItem(
    at: IndexPath(row: 5, section: 0),
    at: .left, // TODO: Left ignores inset
    animated: true
)
myCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
然后添加以下行:

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

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

如果其他人无意中看到滚动到水平集合视图的开头,在考虑部分插图时,我可以通过执行以下操作来实现这一点(在Swift 5.2.4中)。此解决方案利用了UICollectionView是UIScrollView这一事实:

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

试试。从左到下。好主意,但不幸的是对我不起作用。我尝试过:“collectionView.scrollToItem(at:indexPath,at:[.bottom,.left],动画:true)”。我还尝试了不同的变体,如[.top、.left]、.bottom、.top、[.left、.bottom]等。方向是垂直的还是水平的?2.你的手机有多大?e、 g.一次显示一个项目或两个项目或n个数字,我认为这会起作用,但在我的情况下,这根本不是什么。我相信这一点,因为它需要设置contentSize,但我使用的是itemSize.cellForItem要求单元格可见,因此如果要滚动到不可见的索引路径,则无法使用。这是最新的正确答案(在iOS 13上测试)。在iOS 11之前
collectionView.scrollToItem()
是关于collectionView插入的,但在iOS 11及更高版本上,我们需要设置
ContentInsertAdjustmentBehavior=。从不