问题
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