UIView及其子层的动画化

4
我有一个子类化的 UIView,由几个图层组成(大部分是 CAShapeLayers,还有少量的 CATextLayers)。我的问题是,如果我使用动画块beginAnimationscommitAnimations)对UIView的大小进行动画调整并在重写的layoutSubviews中重新布局子图层,则图层不会随着UIView一起动画。

下面是我用于动画UIView框架的代码:
miniView.backgroundColor = [UIColor orangeColor];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationRepeatCount:MAXFLOAT];
[UIView setAnimationRepeatAutoreverses:YES];

miniView.frame = newFrame;

[UIView commitAnimations];

问题在于视图本身可以正常地进行动画处理,但子层却不能。我可以看到视图的大小会增加和缩小,但子层会立即增大并保持新的较大尺寸。当视图大小改变时,调整视图的子层大小的最佳方法是什么?如何使它们以与父视图相同的方式进行动画处理?


你找到这个问题的答案了吗?我和Noah有同样的问题。Brandon提供的解决方案略有不同,因为它只是将子层作为层的一部分进行缩放,而不是在动画期间实际重新绘制它们的新大小。 - Philippe Sabourin
1个回答

1
我需要看更多的代码才能真正解决问题,不过你可以尝试对 miniView 的层进行动画处理,而不是它的视图。
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; 
animation.fromValue = [NSNumber numberWithFloat:0.0];
animation.toValue = [NSNumber numberWithFloat:1.0];
// additional setup...

[miniView.layer layoutIfNeeded];
[miniView.layer addAnimation:animation forKey:@"whateverYouWant"];

不要使用UIKit动画,一旦掌握了这种方法,它会更加灵活。


1
我曾经遇到过类似的问题。这篇文章给了我提示。UIView动画只适用于UIKit视图等...如果您想要对CALayer对象进行动画处理,您需要使用CoreAnimation API而不是UIView animate...方法。 - Matt Connolly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接