Change scrolling position of collection view, when view is currently not visible

时光总嘲笑我的痴心妄想 提交于 2019-12-24 16:42:32

问题


There are two scenarios where I have problem with setting the scrolling position of my collection view:

  • on start up I want to scroll to a certain item (starting position != beginning of the collection view)
  • view is currently not visible yet, but in "background" the collection view should scroll to a certain item

What is a reliable way to scroll the collection view to a certain cell? Currently I'm setting the scrolling position with scrollToItemAtIndexPath in viewDidAppear, but that is too late for me.


回答1:


Try to call the moethod in viewDidLayoutSubview:

Loooks like you cant scroll to item either in viewWillAppear/DidAppear!!!!

YOu can modify the UICollectionViewScrollPositionLeft based on your collection view scroll direction

-(void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];

    NSIndexPath *indexPath=[NSIndexPath indexPathForItem:3 inSection:0]; //indexpath for the item to scroll

    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];

}

Swift:

    func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    var indexPath: NSIndexPath = NSIndexPath.indexPathForItem(3, inSection: 0)
    collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
}    

The method viewDidLayoutSubviews will get called only once, and it doesnt get called based on the collection view scroll!!!

Normally it will get called after viewWillAppear and before viewDidAppear!!




回答2:


Try this:

CGPoint newContentOffset = yourCollectionView.contentOffset;
float offset = selectedIndex * (self.view.bounds.size.width + cellSpacing);
newContentOffset.x += offset;
yourCollectionView.contentOffset = newContentOffset;


来源:https://stackoverflow.com/questions/33737839/change-scrolling-position-of-collection-view-when-view-is-currently-not-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!