UICollectionView scrollToItemAtIndexPath

时间:2013-11-06 15:34:29

标签: ios

我正在尝试滚动到集合视图中的特定项目,并且它似乎在90%的时间内正常发生。我基本上有一个集合视图,其框架我通过自动布局更改,然后我希望我的单元格是所有新框架的大小,所以我设置了一个新的大小。当我在scrollToItemAtIndexPath上放置一个断点时,似乎当它工作时,项目大小已经生效,但是它不起作用的时间,单元格仍然具有旧的大小。如何在滚动之前确保itemSize已更改?

[weakSelf.view removeConstraints:@[weakSelf.verticalSpace, weakSelf.collectionViewBottomSpace, weakSelf.bottomLayoutTopCollectionView]];
[weakSelf.view addConstraints:@[weakSelf.collectionViewToTop, weakSelf.imageHeight, weakSelf.youLabelToTop]];
[UIView animateWithDuration:animated ? .5 : 0.0
                                      animations:^{
                                          [weakSelf.view layoutIfNeeded];
                                      }
                                      completion:^(BOOL finished) {
  UICollectionViewFlowLayout * layout = (UICollectionViewFlowLayout *)self.currentUserCollectionView.collectionViewLayout;

  layout.itemSize = weakSelf.currentUserCollectionView.frame.size;

  [weakSelf.currentUserCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[self getSelectedIndex:selectItem] inSection:0]
                                         atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                                 animated:NO];
}];

2 个答案:

答案 0 :(得分:41)

确保集合视图首先布置其子视图以及在滚动之前调整单元格的大小。我建议将滚动移动到一个你确定所有布局都已完成的地方,如:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    NSIndexPath *indexPath = // compute some index path

    [self.collectionView scrollToItemAtIndexPath:indexPath
                                atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                        animated:YES];
}

答案 1 :(得分:24)

另一种选择是在致电layoutIfNeeded之前致电UICollectionView上的scrollToItemAtIndexPath。这样,每次布置父视图的子视图时,您都不会执行滚动操作。