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

SNV*_*NV7 27 objective-c uiscrollview ios 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];
 }
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*che 35

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

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:endOfModel inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
Run Code Online (Sandbox Code Playgroud)


Fir*_*iro 17

只是详细说明我的评论.

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

在viewWillAppear或viewDidAppear中调用时,大多数这些操作最有效.除了Apple文档之外,还有一个指出在重写这些方法时要做的重要事情:

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

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


小智 9

所以有一个类似的问题,这是另一种方法,而不使用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];
}
Run Code Online (Sandbox Code Playgroud)


mou*_*igo 6

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


Log*_*gan 5

这些对我来说都不太有效,我最终得到了这个,它可以在任何滚动视图上工作

extension UIScrollView {
    func scrollToBottom(animated: Bool) {
        let y = contentSize.height - 1
        let rect = CGRect(x: 0, y: y + safeAreaInsets.bottom, width: 1, height: 1)
        scrollRectToVisible(rect, animated: animated)
    }
}
Run Code Online (Sandbox Code Playgroud)