简体   繁体   English

UICollectionView - 滚动到第一个单元格

[英]UICollectionView - Scrolling to first cell

I'm making use of UICollectionView and I need to scroll to first cell after click in a button. 我正在使用UICollectionView,我需要在单击按钮后滚动到第一个单元格。

The button is located in a (big) header section in my collection view... when clicking int it, I need scroll to my first cell located bellow of this button. 该按钮位于我的集合视图中的(大)标题部分...当点击它时,我需要滚动到位于此按钮下方的第一个单元格。

I created a action of this button, but I don't know how to scroll to first UICollectionViewCell. 我创建了这个按钮的动作,但我不知道如何滚动到第一个UICollectionViewCell。

Can someone help me? 有人能帮我吗?

Use this delegate method, setting the indexPath at the first position: 使用此委托方法,将indexPath设置在第一个位置:

Swift 迅速

self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), 
                                                atScrollPosition: .Top, 
                                                        animated: true)

Swift 3 斯威夫特3

self.collectionView?.scrollToItem(at: IndexPath(row: 0, section: 0), 
                                  at: .top, 
                            animated: true)

Objective-C Objective-C的

[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] 
                            atScrollPosition:UICollectionViewScrollPositionTop
                                    animated:YES];

Change UICollectionViewScrollPositionTop if you want to scroll and stop at a different position 如果要滚动并停在其他位置,请更改UICollectionViewScrollPositionTop

可以使用UIScrollView相关属性

collectionView.contentOffset.x = 0

您可以将此用于Objective-C

        [self.restaurantCollectionView setContentOffset:CGPointZero animated:YES];

The following solution works fine for me: 以下解决方案对我来说很好:

UIView.animate(withDuration: 0.5, animations: {
     self.collectionView?.contentOffset.x = 0
})

It scrolls to the first item and the contentInset can be seen as well. 它滚动到第一个项目,也可以看到contentInset。

默认CollectionView Delgeate ...

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;
if let indexPath = self.collectionView?.indexPathForItem(at: CGPoint(x: 0, y: 0)) {
            self.collectionView?.scrollToItem(at: indexPath, at: .top, animated: false)
}
 scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true)

I found to work reliably on all devices and correctly handle iPhone X-style safe areas. 我发现可以在所有设备上可靠地工作并正确处理iPhone X风格的安全区域。

let top = CGPoint(x: collectionView.contentOffset.x,
                  y: collectionView.adjustedContentInset.top)
collectionView.setContentOffset(top, animated: false)

(This scrolls vertically to the top but you could easily make it scroll to the top-left if you wanted.) (这会垂直滚动到顶部,但如果您愿意,可以轻松滚动到左上角。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM