[英]Reload and Scroll to a specific Collection View cell
我正在编写一个应用程序,它利用 UICollectionView 在 CollectionView 单元格中显示一些内容。 使用捏合手势,需要重新加载集合视图。 我能够根据捏合手势处理内容的变化。 现在,在捏合手势开始时,集合视图需要重新加载并滚动到特定索引。 为此,我调用了这样的函数:
[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];
}
}
希望对某人有帮助
到目前为止我发现的最好的解决方案是使用CATransaction
像这样:
CATransaction.begin()
CATransaction.setCompletionBlock {
collectionView.scrollToItem(...)
}
collectionView.reloadData()
CATransaction.commit()
如果你想垂直滚动,你可以试试这个异步代码
dispatch_async(dispatch_get_main_queue(), ^{
[_yourCollectionView reloadData];
[_yourCollectionView reloadInputViews];
[_yourCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
});
并替换为
[_yourCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
如果你想让你的滚动视图滚动水平
用你想要滚动到的行号替换indexPathForRow和inSection 的数量,并记住UITableView和UICollectionView 的NSIndexPath通常带有inSection引用将 NSInteger 转换为 NSIndexpath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.