自定义UICollectionViewCell contentView动画

时间:2015-09-17 07:26:17

标签: ios objective-c animation uicollectionview uicollectionviewcell

如果用户触摸它,我会更改UICollectionViewCell的高度。为了实现这一点,我使用performBatchUpdates:来更改基础数据并使用标准单元格动画。这非常有效,并且使用标准的增长和缩小动画对变化进行动画处理。

此外,我使用reloadSection更新该部分中单元格的所有子视图。这是我的代码:

[collectionView performBatchUpdates:^{
    dataHelper.isCellExpanded = !dataHelper.isCellExpanded;
 } completion:^(BOOL finished) {
    [collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
}];

我需要对扩展的单元状态的子视图进行灵活的重新排序。所以我不使用自动布局。我只更改子视图框架,并希望动画帧变化和UICollectionViewCell动画。

问题是单元格contentView内的子视图在没有动画的情况下更新,单元格的高度变化动画完成后更新。但是我想为单元格子视图设置动画以及高度变化的动画。如何实现呢?

更新

UICollectionViewCell中的自定义动画方法如下所示:

- (void)animate {
 [UIView animateWithDuration:1.0
                       delay:0.0
                     options:UIViewAnimationOptionCurveLinear
                  animations:^
 {
     CGRect labelFrame = self.testLabel.frame;
     labelFrame.origin.y += 70;
     self.testLabel.frame = labelFrame;
 }
 completion:nil];
}

我在testLabel子类的initWithFrame:中创建了UICollectionViewCell,如下所示:

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
      CGRect cellFrame = CGRectMake(0, 0, frame.size.width, frame.size.height);

      // content
      _testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, frame.size.height - 20, frame.size.width - 20, 20)];
      _testLabel.backgroundColor = [UIColor redColor];
      _testLabel.textColor = [UIColor blackColor];
      _testLabel.text = @"test";
      [self.contentView addSubview:_testLabel];
      ....

2 个答案:

答案 0 :(得分:0)

您必须在集合视图单元格中实现动画方法,并且需要从performBatchUpdates方法调用该方法。

[collectionView performBatchUpdates:^{
    dataHelper.isCellExpanded = !dataHelper.isCellExpanded;
    // Access the cells you want to animate
    yourCustomCell *cell = (yourCustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell animate];
} completion:^(BOOL finished) {
    [collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
}];

在单元格动画方法中,您可以实现所需的所有动画。

答案 1 :(得分:0)

我能够通过以contentView testLabel子类中的UICollectionViewCellautoresizingMask添加弹簧和支柱来解决这个问题。 >

- (id)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
      CGRect cellFrame = CGRectMake(0, 0, frame.size.width, frame.size.height);

      self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

      // content
      _testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, frame.size.height - 20, frame.size.width - 20, 20)];
      _testLabel.backgroundColor = [UIColor redColor];
      _testLabel.textColor = [UIColor blackColor];
      _testLabel.text = @"You rock";
      _testLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
      [self.contentView addSubview:_testLabel];

旁注: 我正在玩AutoLayout来解决这个问题,但却无法让它发挥作用。

相关问题