ios - 重新加载并滚动到特定的 Collection View 单元格

标签 ios objective-c uicollectionview

我正在编写一个应用程序,它使用 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/

相关文章:

iOS - 按比例更改 UILabel 字体大小

ios - 在 UITableview 上滑动删除而不确认

ios - index ScrollTo 不适用于 TableViewCell Swift 中的最后一个 CollectionView

swift - Collection View 单元格内 Collection View 的 ScrollTo indexPath(嵌套 CollectionView)

ios - 将tapGestureRecognizer添加到backgroundview时无法触发collectionview的事件

ios - HTML 特殊键显示在帖子描述中

ios - Swift:不保存 NSUserDefaults.standardUserDefaults 值

iphone - 如何让 iPhone 无限振动

ios - 如何在 IOS 中使用 UIView 打开 PDF 文件

ios - 在 PDFView 中设置内容插入