【发布时间】:2013-03-19 19:54:10
【问题描述】:
在 UIView 子类中,我有这个方法:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * aTouch = [touches anyObject];
CGPoint loc = [aTouch locationInView:self];
CALayer * layer = [CALayer layer];
[layer setBackgroundColor: [[UIColor colorWithHue:(float)rand()/RAND_MAX saturation:1 brightness:1 alpha:1] CGColor]];
[layer setFrame:CGRectMake(0, 0, 64, 64)];
[layer setCornerRadius:7];
[layer setPosition:loc];
[layer setOpacity:0];
[self.layer addSublayer:layer];
CABasicAnimation * opacityAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
opacityAnim.duration=2.42;
opacityAnim.fromValue=[NSNumber numberWithFloat:0];
opacityAnim.toValue= [NSNumber numberWithFloat:1];
opacityAnim.fillMode = kCAFillModeForwards;
opacityAnim.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
opacityAnim.removedOnCompletion=NO;
opacityAnim.delegate=self;
// explicit animation is working as expected
// [layer addAnimation:opacityAnim forKey:@"opacityAnimation"];
// Why isn't the implicit animation working ?
[layer setOpacity:1];
}
我错过了什么?我希望 CALayer layer 的不透明度使用此方法的最后一行进行隐式动画处理。
我的解决方案
感谢邓肯的回答,这是我解决问题的方法。
-(CALayer *) layerFactory:(CGPoint) loc {
CALayer * layer = [CALayer layer];
[layer setBackgroundColor: [[UIColor colorWithHue:(float)rand()/RAND_MAX saturation:1 brightness:1 alpha:1] CGColor]];
[layer setFrame:CGRectMake(0, 0, 64, 64)];
[layer setCornerRadius:7];
[layer setPosition:loc];
[layer setOpacity:0];
return layer;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * aTouch = [touches anyObject];
CGPoint loc = [aTouch locationInView:self];
[CATransaction begin];
CALayer * layer = [self layerFactory:loc];
[self.layer addSublayer:layer];
[CATransaction commit];
[CATransaction begin];
[CATransaction setAnimationDuration:0.45];
[layer setOpacity:1];
[CATransaction commit];
}
您只需要将图层的创建和不透明度的修改放在两个不同的 CATransaction 块中。但是,将层的创建(而不是添加)移动到 layerFactory 方法并不会改变这种情况。
我不知道这是否是最好的解决方案,但它确实有效。
【问题讨论】:
-
这是否意味着隐式动画可以在主 UIView 层的子层上但在层本身上完成?
-
接受的答案不正确。在此处查看正确答案:stackoverflow.com/a/10456080/56149。
标签: ios core-animation