屏幕加载时,UICollectionView会自动滚动到底部

我想弄清楚当屏幕第一次加载时如何一直滚动到UICollectionView的底部。 我可以在触摸状态栏时滚动到底部,但我希望能够在视图加载时自动执行此操作。 如果我想在触摸状态栏时滚动到底部,下面的工作正常。

- (BOOL)scrollViewShouldScrollToTop:(UITableView *)tableView { NSLog(@"Detect status bar is touched."); [self scrollToBottom]; return NO; } -(void)scrollToBottom {//Scrolls to bottom of scroller CGPoint bottomOffset = CGPointMake(0, collectionViewReload.contentSize.height - collectionViewReload.bounds.size.height); [collectionViewReload setContentOffset:bottomOffset animated:NO]; } 

我试过在viewDidLoad中调用[self scrollToBottom]。 这不起作用。 有关如何在视图加载时滚动到底部的任何想法?

只是详细说明我的评论。

viewDidLoad在元素可视化之前被调用,因此某些UI元素无法很好地操作。 比如在工作中移动按钮但处理子视图通常不会(比如滚动CollectionView)。

在viewWillAppear或viewDidAppear中调用时,大多数这些操作最有效。 以下是Apple文档中的一个除了指出在覆盖这些方法中的任何一个时要做的重要事情:

您可以覆盖此方法以执行与显示视图相关的其他任务。 如果重写此方法,则必须在实现中的某个时刻调用super。

超级调用通常在自定义实现之前调用。 (所以重写方法中的第一行代码)。

我发现viewWillAppear没有任何效果。 我只能在viewDidLayoutSubviews中使用它:

 - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:endOfModel inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO]; } 

所以有一个类似的问题,这是另一种方法, 而不使用scrollToItemAtIndexPath

仅当内容大于视图框时,才会滚动到底部。

使用scrollToItemAtIndexPath可能更好,但这只是另一种方法。

 CGFloat collectionViewContentHeight = myCollectionView.contentSize.height; CGFloat collectionViewFrameHeightAfterInserts = myCollectionView.frame.size.height - (myCollectionView.contentInset.top + myCollectionView.contentInset.bottom); if(collectionViewContentHeight > collectionViewFrameHeightAfterInserts) { [myCollectionView setContentOffset:CGPointMake(0, myCollectionView.contentSize.height - myCollectionView.frame.size.height) animated:NO]; } 

Swift 3的例子

 let sectionNumber = 0 self.collectionView?.scrollToItem(at: //scroll collection view to indexpath NSIndexPath.init(row:(self.collectionView?.numberOfItems(inSection: sectionNumber))!-1, //get last item of self collectionview (number of items -1) section: sectionNumber) as IndexPath //scroll to bottom of current section , at: UICollectionViewScrollPosition.bottom, //right, left, top, bottom, centeredHorizontally, centeredVertically animated: true) 

获取最后一项的索引路径。 然后…

 - (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated 

对我来说,我找到了下一个解决方案

在CollectionView中调用reloadData,并在main上进行dcg滚动。

  __weak typeof(self) wSelf = self; [wSelf.cv reloadData]; dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"HeightGCD:%@", @(wSelf.cv.contentSize.height)); [wSelf.cv scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:50 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES]; });