2

我正在编写一个应用程序,它利用 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 没有任何单元格可以滚动。

重新加载完成后如何滚动到索引路径?任何帮助都会很棒!

4

3 回答 3

0

到目前为止,我发现的最佳解决方案是这样使用CATransaction

CATransaction.begin()
CATransaction.setCompletionBlock {
    collectionView.scrollToItem(...)
}

collectionView.reloadData()

CATransaction.commit()
于 2020-07-16T07:29:08.067 回答
0

尝试这个

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];
  }
}

希望对某人有帮助

于 2018-05-24T09:41:31.810 回答
-1

如果你想滚动垂直,你可以试试这个异步代码

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];

如果你想要你的滚动视图滚动水平

将indexPathForRowinSection的数量替换为您要滚动到的行号,并记住UITableViewUICollectionViewNSIndexPath通常带有inSection引用将 NSInteger 转换为 NSIndexpath

于 2014-11-17T04:34:06.597 回答