我正在编写一个应用程序,它使用 UICollectionView 在 CollectionView 单元格中显示一些内容。使用捏合手势,需要重新加载 Collection View 。我能够根据捏合手势处理内容的变化。现在,在捏合手势开始时, Collection View 需要重新加载并滚动到特定索引。为此,我调用了这样的函数:
[tempCollectionView reloadData];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scrollToItem) userInfo:nil repeats:YES];
[OR]
[self performSelector:@selector(scrollToItem) withObject:nil afterDelay:0.0];
- (void) scrollToItem
{
if (m_selectedCellIndex == -1)
{
NSLog(@"cell return");
return;
}
NSIndexPath *iPath = [NSIndexPath indexPathForItem:m_selectedCellIndex inSection:0];
[tempLocalFilesCollectionView scrollToItemAtIndexPath:iPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
LocalFilesCollectionViewCell *cell = (LocalFilesCollectionViewCell *) [m_tempLocalFilesCollectionView cellForItemAtIndexPath: iPath];
if (cell)
{
CGPoint p = [tempCollectionView convertPoint: cell.center fromView: tempCollectionView];
NSLog(@"center: %f, %f, %f, %f", cell.center.x, cell.center.y, p.x, p.y);
}
else
{
NSLog(@"Not found");
}
}
但是滚动不起作用。它因错误“尝试滚动到无效的索引路径”而崩溃。很明显 tempCollectionView 没有任何单元格可以滚动。
重新加载完成后如何滚动到索引路径?任何帮助都会很棒!
最佳答案
试试这个
BOOL _viewDidLayoutSubviewsForTheFirstTime = YES;
- (void)viewDidLoad
{
[super viewDidLoad];
_viewDidLayoutSubviewsForTheFirstTime = YES;
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
// Only scroll when the view is rendered for the first time
if (_viewDidLayoutSubviewsForTheFirstTime) {
_viewDidLayoutSubviewsForTheFirstTime = NO;
// Calling collectionViewContentSize forces the UICollectionViewLayout to actually render the layout
[self.collectionView.collectionViewLayout collectionViewContentSize];
// Now you can scroll to your desired indexPath or contentOffset
[self.collectionView scrollToItemAtIndexPath:yourDesiredIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}
}
希望对某人有帮助
关于ios - 重新加载并滚动到特定的 Collection View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19788788/