2
在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塊modifiction。但是,將圖層的創建(而不是添加)移動到layerFactory方法並不會改變情況。
我不知道這是否是最好的解決方案,但它的工作。
所以這意味着隱式動畫可以在主UIView圖層的子圖層上完成,但是在圖層本身上? – Sam 2013-10-31 11:30:10
接受的答案不正確。在這裏看到正確的答案:http://stackoverflow.com/a/10456080/56149。 – an0 2014-04-09 23:55:02
[核心動畫隱式動畫的可能重複不會觸發,除非在事件循環中](http://stackoverflow.com/questions/10456022/core-animation-implicit-animation-doesnt-fire-unless-in-event-loop ) – an0 2014-04-09 23:56:18