当视图当前不可见时,更改集合视图的滚动位置

有两种情况下,我设置我的collections视图的滚动位置有问题:

  • 在开始时,我想滚动到某个项目(起始位置!=集合视图的开始)
  • 视图目前还不可见,但在“背景”集合视图应滚动到某个项目

将集合视图滚动到某个单元格的可靠方法是什么? 目前我设置scrollToItemAtIndexPathviewDidAppear的滚动位置,但对于我来说已经太晚了。

尝试在viewDidLayoutSubview调用moethod:

像你不能滚动到项目的任何viewWillAppear/DidAppear !!!!

你可以修改UICollectionViewScrollPositionLeft根据你的collections视图的滚动方向

 -(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将被调用一次,它不会被调用基于集合视图滚动!

通常它会在viewWillAppearviewDidAppear之前被调用!

尝试这个:

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