【问题标题】:How do I animate the inner views of a collection view cell while changing it's size?如何在更改集合视图单元格的大小时为其内部视图设置动画?
【发布时间】:2013-11-22 03:41:38
【问题描述】:

我有一个集合视图,我想要的效果是,当一个单元格被点击时,它会增长到占据整个屏幕。为此,我基本上只是在didSelectItemAtIndexPath 中调用performBatchUpdates,而sizeForItemAtIndexPath 知道为选定的单元格返回更大的尺寸。这一切都很好,细胞会根据需要生长和收缩。

问题出在单元格内部。集合视图单元由由约束管理的适度复杂的视图层次结构组成。我希望单元格的子视图随着动画单元格的增长和收缩。不幸的是,随着单元格慢慢动画到它的新大小,我的子视图立即捕捉到它们的新位置。如何确保单元格内容与单元格大小一致?

以下是集合视图控制器中的两个相关方法:

- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([collectionView.indexPathsForSelectedItems containsObject:indexPath])
    return CGSizeMake(collectionView.bounds.size.width - 20, collectionView.bounds.size.height - (20 + [self.topLayoutGuide length]));
else
    return CGSizeMake(260, 100); 
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView performBatchUpdates:nil completion:nil];
}

【问题讨论】:

  • 您的子视图很可能会卡入到位,因为某些表示正在展开的单元格的标志从 false 切换为 true,然后调用 layoutSubviews,这会立即将子视图移动到展开的位置。不过我只是在猜测——如果您添加代码,我们将能够看到是否是这种情况。另一方面 - 单元格是否应该在集合中其他单元格的顶部展开,还是应该将它们推开?如果它应该在顶部展开,我建议在 UICollectionView 上方添加一个新视图并为其设置动画。
  • 我添加了两个相关的方法来调整选择的大小。视图控制器中几乎没有其他代码。单元格本身是一些 nib 文件,我可以轻松添加到帖子中。

标签: ios autolayout


【解决方案1】:

我遇到了完全相同的问题。经过多次尝试,以下代码为我解决了问题。在持续时间为 3.0(+- 批处理更新持续时间)的批量更新之后直接调用 layoutIfNeed 会为约束设置动画。

[self performBatchUpdates:nil completion:nil];

// IndexPath of cell to be expanded
UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
[UIView animateWithDuration:0.3 animations:^{
    [cell.contentView layoutIfNeeded];
}];

【讨论】:

  • 谢谢你让我免于在这里发疯。
  • 是的,这确实有效,我用它解决了同样的问题
【解决方案2】:

我想扩展 Antoine 的回答。在动画块内调用performBatchUpdates:completion: 实际上会设置单元格调整大小的持续时间并匹配内容调整大小。

[UIView animateWithDuration:0.3 animations:^{
    [self performBatchUpdates:^{
        // set flags needed for new cell size calculation
    } completion:nil];
    [collectionView layoutIfNeeded];
}];

这样你也可以玩动画时间,甚至使用弹簧动画。

【讨论】:

    【解决方案3】:

    我也有同样的问题。将这些添加到 CollectionViewCell 的子类中。它对我有用。

    // ProblematicCollectionViewCell.swift
    
    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
       layoutIfNeeded()
    }
    

    这里是原始链接:https://codedump.io/share/LXZwAOOMxafU/1/uicollectionviewcell---contents-do-not-animate-alongside-cell39s-contentview 答案在 cmets 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多