我有许多 CAShapeLayers 已经是视图层 (UIView) 的子层。我可以毫无困难地为他们的路径设置动画。但是,我需要稍后添加一些额外的形状图层,然后为所有形状图层的所有路径设置动画。当我尝试插入新的子层时,动画不再出现。视图以最终状态的所有形状图层进行渲染。
这是我正在处理的代码块。当我将其注释掉时,现有图层的路径动画效果很好。有人可以告诉我发生了什么事吗?
for (int i = oldPoints.count; i < newPoints.count; i++)
[self.layer insertSublayer: [CAShapeLayer layer] atIndex: ++layerIndex];
另外,我尝试调用 -addSublayer: 并且得到相同的结果。
我的超级视图中的动画代码如下所示:
[UIView animationWithDuration: 0.2
animations: ^{
for (ComponentView *view in _componentViews)
[view reloadDataWithAnimation: YES];
[self layoutComponentViews];
}
completion: ^(BOOL finished) {
}];
在 -reloadDataWithAnimation: 在我的 ComponentView 中,我有以下代码:
- (void) reloadDataWithAnimation: (BOOL) animate {
for (int rowIndex = 0; rowIndex < oldData.count; rowIndex++) {
NSArray *oldPoints = [oldData objectAtIndex: rowIndex];
NSArray *newPoints = nil;
if (rowIndex < newData.count)
newPoints = [newData objectAtIndex: rowIndex];
if (newPoints.count > oldPoints.count) {
layerIndex += oldPoints.count;
for (int i = oldPoints.count; i < newPoints.count; i++)
[self.layer insertSublayer: [CAShapeLayer layer] atIndex: ++layerIndex];
}
else if (newPoints.count < oldPoints.count) {
layerIndex += newPoints.count;
for (int i = newPoints.count; i < oldPoints.count; i++)
[disposableLayers addObject: [self.layer.sublayers objectAtIndex: ++layerIndex]];
}
else {
if (newPoints.count > 0)
layerIndex += newPoints.count;
}
}
if (newData.count > oldData.count) {
for (int rowIndex = oldData.count; rowIndex < newData.count; rowIndex++) {
NSArray *newPoints = [newData objectAtIndex: rowIndex];
for (int i = 1; i < newPoints.count; i++)
[self.layer insertSublayer: [CAShapeLayer layer] atIndex: ++layerIndex];
}
}
/* code that iterates through old and new data structures */
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath: @"path"];
[animation setFromValue: (__bridge id) oldPath];
[animation setToValue: (__bridge id) newPath];
[animation setFillMode: kCAFillModeForwards];
[animation setDuration: _defaultAnimationDuration];
CAShapeLayer *shapeLayer = (CAShapeLayer *) [self.layer.sublayers objectAtIndex: layerIndex];
[shapeLayer setPath: newPath];
[shapeLayer setStrokeColor: [self strokeColorForItemAtIndexPath: indexPath].CGColor];
[shapeLayer setLineWidth: self.lineWidth];
[shapeLayer addAnimation: animation forKey: @"path"];
}
谢谢!