如何为 NSCollectionView 的 scrollToIndexPaths:scrollPosition: 设置动画?

How to animate NSCollectionView's scrollToIndexPaths:scrollPosition:?

我正在尝试为 NSCollectionView 的 scrollToIndexPaths:scrollPosition: 制作动画,根据文档,如果将此消息发送到集合视图的 animator 代理,则可以实现这一点。但是,我无法让它工作。

我建立了一个非常简单的项目,其中仅包含一个集合视图并创建了 1000 个 100x100 项目。一个简单的操作将可见索引路径递增 50 并尝试滚动到它。我的滚动代码如下所示:

- (IBAction)increment:(id)sender {
  NSIndexPath *visibleIndexPath = [[self.collectionView indexPathsForVisibleItems] anyObject];
  NSIndexPath *toIndexPath = [NSIndexPath indexPathForItem:visibleIndexPath.item + 50 inSection:visibleIndexPath.section];
  [self.collectionView.animator scrollToItemsAtIndexPaths:[NSSet setWithObject:toIndexPath] scrollPosition:NSCollectionViewScrollPositionCenteredHorizontally];
}

这会将集合视图跳转到目标索引路径,但不会设置动画。我已确保滚动视图也有层支持,基于我在此发现的一些其他线程:

项目中唯一的其他代码是在 viewDidLoad: 中设置集合视图和流布局的几行代码:

  // Do any additional setup after loading the view.
  NSCollectionViewFlowLayout *flowLayout = [[NSCollectionViewFlowLayout alloc] init];
  flowLayout.itemSize = CGSizeMake(100.f, 100.f);
  flowLayout.scrollDirection = NSCollectionViewScrollDirectionHorizontal;
  self.collectionView.collectionViewLayout = flowLayout;

  [self.collectionView registerClass:[CollectionViewItem class] forItemWithIdentifier:@"identifier"];

有没有人能够使用 scrollToIndexPaths:scrollPosition: 制作动画?文档使它听起来很明显,但我无法让它工作。

尝试将您的 scrollToIndexPaths:scrollPosition 放入动画标签中

参见: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/clm/UIView/animateWithDuration:animations:

我遇到了同样的问题并花了一些时间来解决它。他们有一个隐式动画的概念,可以处理非 属性 变化的代码。 IE。看起来 animator 会对某些属性进行动画处理,但不会对其他布局更改进行动画处理。要允许这些 "other" 更改被动画化,您必须将允许隐式动画设置为当前动画上下文。这是我的工作代码:

let ctx = NSAnimationContext.current()
ctx.allowsImplicitAnimation = true

collectionView.animator().scrollToItemsAtIndexPaths(Set<NSIndexPath>(arrayLiteral: nextPath), scrollPosition: .TrailingEdge)

注意:我编辑了代码片段以支持更新的 Swift 语法。

因为我的应用程序是在 ObjectiveC 中,所以我翻译了上面的答案 Swift,并在实际代码中进行了测试:

[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.5];
[NSAnimationContext currentContext].allowsImplicitAnimation=YES;
[[myCollectionView animator] scrollToItemsAtIndexPaths:myIndexPathSet scrollPosition:NSCollectionViewScrollPositionNearestHorizontalEdge];
[NSAnimationContext endGrouping];