xcode CollectionView 滚动到顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39490840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:14:33  来源:igfitidea点击:

CollectionView scroll to top

iosobjective-cxcodescrolluicollectionview

提问by KAR

I have one CollectionViewController and have 10 cells in it.

我有一个 CollectionViewController,里面有 10 个单元格。

But when I run the app it displays the cell at bottom, but I want to display it from top cell at viewDidLoad.

但是当我运行应用程序时,它会在底部显示单元格,但我想在 viewDidLoad 中从顶部单元格显示它。

I tried many things but it didn't work.

我尝试了很多东西,但没有奏效。

How to fix it?

如何解决?

采纳答案by User511

Add this line after reloading the collection view.

重新加载集合视图后添加此行。

[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];

Edit:

编辑:

Just want to add one more point here is if collectionView datasource has ZERO elements or it is nilthen above code will not work and probably crash your app.

只是想在这里再补充一点,如果 collectionView 数据源具有零元素,或者nil上面的代码将不起作用并且可能会导致您的应用程序崩溃。

Write condition to check that datasource is available or not!

编写条件以检查数据源是否可用!

if (self.dataArray.count > 0) {
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}

Where, dataArrayis your datasource.

哪里,dataArray是你的数据源。

回答by Lam Nguyen

in swift 3: after reloadData()

在 swift 3 中:在 reloadData() 之后

  self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)

回答by Vinith

Add this piece of code after reloading the collection view:

重新加载集合视图后添加这段代码:

swift

迅速

yourCollectionView.setContentOffset(CGPoint.zero, animated: true)

yourCollectionView.setContentOffset(CGPoint.zero, animated: true)

objective-c

目标-c

[yourCollectionView setContentOffset:CGPointZero animated:YES];

[yourCollectionView setContentOffset:CGPointZero animated:YES];

回答by CSE 1994

Its work fine......

它的工作正常......

collectionView.setContentOffset(.zero, animated: false)

回答by erdikanik

Make animated option false. Maybe some view animations are running during your collection view animation process.

将动画选项设为 false。也许一些视图动画在您的集合视图动画过程中正在运行。

collectionView.scrollToItem(at: indexPath, at: .top, animated: false)

回答by Monika Patel

Please try this one

请试试这个

[self.yourcollectionview scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];

回答by JigneshP

To display the data from top cell in collectionView you can use one method

要在 collectionView 中显示来自顶部单元格的数据,您可以使用一种方法

[collectionView setScrollsToTop:YES];

Hope it will Help You.

希望它会帮助你。