UICollectionView动画数据更改

Nim*_*od7 80 ios uicollectionview

在我的项目中,我使用UICollectionView来显示图标网格.

用户可以通过单击分段控件来更改排序,该分段控件使用不同的NSSortDescriptor调用从核心数据中获取.

数据量始终相同,只是以不同的部分/行结束:

- (IBAction)sortSegmentedControlChanged:(id)sender {

   _fetchedResultsController = nil;
   _fetchedResultsController = [self newFetchResultsControllerForSort];

   NSError *error;
   if (![self.fetchedResultsController performFetch:&error]) {
       NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
   }

   [self.collectionView reloadData];
}
Run Code Online (Sandbox Code Playgroud)

问题是reloadData没有为更改设置动画,UICollectionView只是弹出新数据.

我应该跟踪更改前后单元格中的哪个indexPath,并使用[self.collectionView moveItemAtIndexPath:toIndexPath:]来执行更改动画,还是有更好的方法?

我没有太多进入子类化collectionViews所以任何帮助将是伟大的...

比尔,谢谢.

pau*_*kow 143

结束语-reloadData-performBatchUpdates:似乎没有引起一个截面集合视图动画.

[self.collectionView performBatchUpdates:^{
    [self.collectionView reloadData];
} completion:nil];
Run Code Online (Sandbox Code Playgroud)

但是,此代码有效:

[self.collectionView performBatchUpdates:^{
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
} completion:nil];
Run Code Online (Sandbox Code Playgroud)

  • 文档中的注释:您不应该在插入或删除项目的动画块中间调用重载数据方法.插入和删除会自动使表的数据得到适当更新. (9认同)
  • 值得注意的是,您不需要围绕reloadSections包裹的self.collectionView performBatchUpdates调用即可获取动画。实际上,在某些情况下,“ performBatchUpdates”调用可能会导致意外的闪烁/单元格调整问题。 (2认同)

Str*_*pes 67

reloadData不会设置动画,也不会在放入UIView动画块时可靠地执行此操作.它想要在UICollecitonView performBatchUpdates块中,所以尝试更像:

[self.collectionView performBatchUpdates:^{
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
} completion:^(BOOL finished) {
    // do something on completion 
}];
Run Code Online (Sandbox Code Playgroud)

  • 这对我的单节集合视图不起作用.我没有得到错误,但也没有动画.替换`-reloadSections:`使它工作. (12认同)
  • 这个答案是不正确的,因为我的情况将在reloadData将performBatchUpdates崩溃我的应用程序,并说该细胞计数不是前后一致.使用reloadSections解决了我的问题.Apple的文档还表明不要在动画块中调用reloadData (9认同)
  • 是的,这似乎工作,但只有你保存节号...否则我收到"无效的节数.更新(10)后集合视图中包含的节数必须等于数量更新前的集合视图中包含的部分(16)".我必须手动插入/删除部分...无论如何被接受!谢谢. (5认同)

Yar*_*sim 65

这就是我为动画重新加载ALL SECTIONS所做的工作:

[self.collectionView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.collectionView.numberOfSections)]];
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

let range = Range(uncheckedBounds: (0, collectionView.numberOfSections))
let indexSet = IndexSet(integersIn: range)
collectionView.reloadSections(indexSet)
Run Code Online (Sandbox Code Playgroud)


Gab*_*nyu 6

对于Swift用户,如果您的collectionview仅包含一个部分:

self.collectionView.performBatchUpdates({
                    let indexSet = IndexSet(integersIn: 0...0)
                    self.collectionView.reloadSections(indexSet)
                }, completion: nil)
Run Code Online (Sandbox Code Playgroud)

/sf/answers/2940097261/所示