当视图当前不可见时,更改集合视图的滚动位置 [英] Change scrolling position of collection view, when view is currently not visible
问题描述
我在设置集合视图的滚动位置时遇到两种情况:
There are two scenarios where I have problem with setting the scrolling position of my collection view:
- 在启动时,我想滚动到某个项目(起始位置!= 集合视图的开头)
- 视图目前还不可见,但在背景"中,集合视图应该滚动到某个项目
将集合视图滚动到某个单元格的可靠方法是什么?目前我正在 viewDidAppear
中使用 scrollToItemAtIndexPath
设置滚动位置,但这对我来说为时已晚.
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.
推荐答案
尝试调用viewDidLayoutSubview
中的方法:
看起来您无法在 viewWillAppear/DidAppear
中滚动到项目!!!!
Loooks like you cant scroll to item either in viewWillAppear/DidAppear
!!!!
您可以根据您的集合视图滚动方向修改UICollectionViewScrollPositionLeft
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];
}
斯威夫特:
func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var indexPath: NSIndexPath = NSIndexPath.indexPathForItem(3, inSection: 0)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
}
viewDidLayoutSubviews
方法只会被调用一次,并且不会基于集合视图滚动而被调用!!!
The method viewDidLayoutSubviews
will get called only once, and it doesnt get called based on the collection view scroll!!!
通常它会在 viewWillAppear
之后和 viewDidAppear
之前被调用!!
Normally it will get called after viewWillAppear
and before viewDidAppear
!!
这篇关于当视图当前不可见时,更改集合视图的滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!