I am having an issue with iOS CABasicAnimation. No matter what I do, I cannot get the methods animationDidStart: and animationDidStop:finished: to fire. My class is subclassing CAShapeLayer and is performing the animations inside of it:
- (void)start{
[self removeAllAnimations];
CABasicAnimation *pathAnimation = [self makeAnimationForKey:#"strokeEnd"];
[self addAnimation:pathAnimation forKey:#"strokeEnd"];
}
- (CABasicAnimation *)makeAnimationForKey:(NSString *)key {
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:key];
anim.fromValue = [NSNumber numberWithFloat:0.f];
anim.toValue = [NSNumber numberWithFloat:1.f];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.duration = self.duration;
anim.delegate = self;
return anim;
}
- (void)animationDidStart:(CAAnimation *)anim{
NSLog(#"HERE START");
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
NSLog(#"HERE STOP");
}
Any tips or help would be appreciated, thanks in advance!
you must set delegate before assigning animation to layer:
popIn.delegate = self;
[annotation.layer addAnimation:popIn forKey:#"popIn"];
Swift 5.4.2
popIn.delegate = self
annotation.layer.add(transition, forKey:"popIn")
Ok so it turns in my subclass I had a property called duration. Even though it is not documented as being apart of CALayer, duration is a part of one of it's protocols called CAMediaTiming. The methods were never fired because the property was being overwritten via my subclass.
Related
I have an insert animation for UICollectionCell (like slide-in), I called the insert animation in this method -collectionView:willDisplayCell:forItemAtIndexPath:.
Everything just works fine when I called this [self.collectionView reloadData]; to reload data. In this way, the animation will be shown currently.
------------
A
------------
<= inserted C (slide-in Animation)
------------
B
------------
But when I tried to add another animation to this inserted cell (like slide-down), things went wrong.
Instead of using -reloadData, I used [self.collectionView performBatchUpdates:completion:] and a custom UICollectionViewFlowLayout with initialLayoutAttributesForAppearingItemAtIndexPath method to implement the slide down animation.
------------
A
------------
------------ <= inserted C (Second, slide-in animation)
B (First, slide-down animation)
------------
In the cell, the log of animation's delegate method animationDidStop:finished: shows that the finished = NO
UICollectionCell:
- (void)setAnimationInLayer:(CALayer *)layer
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"transform.translation.x"];
anim.fromValue = [NSNumber numberWithFloat:(layer.bounds.size.width * 0.33f)];
anim.toValue = [NSNumber numberWithFloat:0.0];
CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:#"opacity"];
opacityAnim.fromValue = [NSNumber numberWithFloat:0];
opacityAnim.toValue = [NSNumber numberWithFloat:1];
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:anim,opacityAnim, nil];
animGroup.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
animGroup.duration = 5.5f;
animGroup.delegate = self;
[layer addAnimation:animGroup forKey:nil];
}
- (void)animationDidStart:(CAAnimation *)animation
{
NSLog(#"-------> %s",__func__);
NSLog(#"%f",[self.articlesCollection.layer presentationLayer].frame.origin.x);
}
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)finished
{
NSLog(#"-------> %s finished: %d",__func__,finished);
NSLog(#"%f",[self.articlesCollection.layer presentationLayer].frame.origin.x);
}
To sum up, when I use -performBatchUpdates:completion instead of -reloadData, every animation of UICollectionView disappeared.
So the question is what situation may cause an animation disappear?
I mean looks like it has been removed from the layer it is attached to. But I didn't do that. Any idea?
How to identify CAAnimation after completion? I tried KVO by setting a string value as animationID and checking it in animationDidStop method. But KVO returns an integer sometimes instead of a string animationID and the app is crashing.
Here is my code:
-(void)moveLayer:(CALayer*)layer to:(CGPoint)point duration:(NSTimeInterval)duration animationID:(NSString*)animationid
{
// Prepare the animation from the current position to the new position
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [layer valueForKey:#"position"];
[animation setDuration:duration];
animation.toValue = [NSValue valueWithCGPoint:point];
animation.delegate=self;
[animation setValue:animationid forKey:#"animationID"];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
// Update the layer's position so that the layer doesn't snap back when the animation completes.
layer.position = point;
// Add the animation, overriding the implicit animation.
[layer addAnimation:animation forKey:#"position"];
}
and callback is:
- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag
{
if (flag) {
id animationIDString=[animation valueForKey:#"animationID"];
// this is coming as an int value sometimes and the code below this fails ..
if([animationIDString isEqual:#"animation1"]) {
//animation is animation1
_movieBalloonImageView.hidden=NO;
_storiesBalloonImageView.hidden=NO;
_rhymesBalloonImageView.hidden=NO;
[self.navigationController popViewControllerAnimated:NO];
}
}
}
What can be the possible reason? Is it because the animation gets destroyed before this delegate gets called?
I am setting removedOnCompletion to NO and fillmode to kCAFillModeForwards.But the code is not working as expected.
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
Or is there any alternative method to do this? I am calling the moveLayer method in several places in the viewController.
Good Evening!
I have a peace of code but it is not calling the animationdidstop method. I could not identify why it does not work. I`ve tried many solutions..
-(IBAction)MakeCircle:(id)sender{
// Add to parent layer
[self.view.layer addSublayer:circle];
// Configure animation
drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.duration = 5.0;
drawAnimation.repeatCount = 1.0;
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
// Add the animation
[circle addAnimation:drawAnimation forKey:#"drawCircleAnimation"];}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
if(anim == [self.view.layer animationForKey:#"drawCircleAnimation"]){
Label.text = [NSString stringWithFormat:#"Loser"];
}
}
Thanks!!
You are not setting yourself as the delegate of the animation. Add this line before adding the animation:
drawAnimation.delegate = self;
Edit:
Oh. I know exactly what the problem is. The system copies your animation object when you submit the animation, so it won't be the same object in the completion routine. Try adding a unique key to the animation and checking that instead of checking to see if it's the same animation object you submitted.
e.g.:
drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
[drawAnimation setValue: #"mydrawCircleAnimation" forKey: #"animationKey"];
//The rest of your animation code...
Then in your animationDidStop:
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
if([anim valueForKey: #"animationKey"
isEqualToString: #"mydrawCircleAnimation"])
{
Label.text = [NSString stringWithFormat:#"Loser"];
}
}
Edit #2:
There is an even cleaner way to handle animation completion code. You can attach a block to your animations and then write a general animationDidStop:completion: method that looks for the block and invokes it if found. See my answer in this thread:
How to identify CAAnimation within the animationDidStop delegate?
There are a lot of related questions, but this situation does not seem to be addressed by any the existing questions.
I have created a view with a custom layer so that one of the properties can be animated. Using the CABasicAnimation class, the animation works correctly.
However, I need a little more control over the animation, such as the ease in and ease out and sequential animations and tried to switch to using block animations. However, when I do that, the animation completes immediately rather than animating over time.
How can I get this block animation to work correctly?
Working animation code:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"inputValue"];
animation.duration = DEFAULT_ANIMATION_DURATION;
if (flipped) {
animation.fromValue = [NSNumber numberWithDouble:0.0];
animation.toValue = [NSNumber numberWithDouble:1.0];
self.myLayer.inputValue = 1.0;
} else {
animation.fromValue = [NSNumber numberWithDouble:1.0];
animation.toValue = [NSNumber numberWithDouble:0.0];
self.myLayer.inputValue = 0.0;
}
[self.layer addAnimation:animation forKey:#"animateInputValue"];
Animation that incorrectly completes immediately, but finished is YES:
[UIView animateWithDuration:10.0 delay:0.0 options:0 animations:^{
self.myLayer.inputValue = 1.0;
} completion:^(BOOL finished) {
NSLog(#"done %#", finished?#"and finished":#", but not finished");
}];
The CALayer being animated:
#import "UViewLayer.h"
#import "YoYouStyleKit.h"
#implementation UViewLayer
+ (BOOL)needsDisplayForKey:(NSString *)key {
if( [key isEqualToString:#"inputValue"] )
return YES;
return [super needsDisplayForKey:key];
}
- (void)setInputValue:(CGFloat)inputValue {
_inputValue = inputValue;
[self setNeedsDisplay];
}
- (void)drawInContext:(CGContextRef)context {
UIGraphicsPushContext(context);
[YoYouStyleKit drawUShapeWithFrame:self.bounds input:self.inputValue];
UIGraphicsPopContext();
}
Adding #dynamic inputValue; in the custom layer seems to make no difference.
Do not mix UIKit and Core Animation animations.
Implement like this:
[CATransaction begin];
[CATransaction setCompletionBlock:^
{
NSLog(#"done");
}];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"inputValue"];
animation.duration = DEFAULT_ANIMATION_DURATION;
if (flipped)
{
animation.fromValue = [NSNumber numberWithDouble:0.0];
animation.toValue = [NSNumber numberWithDouble:1.0];
self.myLayer.inputValue = 1.0;
}
else
{
animation.fromValue = [NSNumber numberWithDouble:1.0];
animation.toValue = [NSNumber numberWithDouble:0.0];
self.myLayer.inputValue = 0.0;
}
[self.layer addAnimation:animation forKey:#"animateInputValue"];
[CATransaction commit];
In addition to Leo Natan's answer, as mentioned in the Apple docs :
Custom layer objects ignore view-based animation block parameters and
use the default Core Animation parameters instead.
What's more tricky is that you can animate the UIView's own layer properties, provided you change one of the animatable properties.
For custom properties like your layer inputValue, you can provide the CABasicAnimation in your layer (id<CAAction>)actionForKey:(NSString *)key but it will not use the UIView animation parameters (duration...).
This animation will play when you change the layer property in the UIView block animation, but it will also play when you simply set the value.
The code provided by Leo Natan is the easiest when to animate your layer from the UIView.
When I launch my application and go to flipSideViewController from mainViewController the image view in flipSideViewController will animate. I want to animate it every time the user
transitions from mainViewController to flipSideViewController.
Here's some code:
[self animate];
//Not sure where to put this instance method. Would I put this in a certain method? I have no idea what I would write for it!
- (void)animate
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
animation.toValue = [NSNumber numberWithFloat:((-10*M_2_PI)/180)];
animation.duration = .3;
animation.autoreverses = YES;
animation.repeatCount = 4;
animation.speed = 9;
pwAnimation.removedOnCompletion = YES;
[_ImageView.layer addAnimation:pwAnimation forKey:#"rotation"];
}
Use ViewDidAppear delegate method of flipSideViewController to invoke your -animate method