Access Method After UIImageView Animation Finish
Solution 1
Use performSelector:withObject:afterDelay:
:
[self performSelector:@selector(animationDidFinish:) withObject:nil
afterDelay:instructions.animationDuration];
or use dispatch_after
:
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, instructions.animationDuration * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self animationDidFinish];
});
Solution 2
You can simple use this category UIImageView-AnimationCompletionBlock
And for Swift version: UIImageView-AnimationImagesCompletionBlock
Take a look on ReadMe file in this class..
Add UIImageView+AnimationCompletion.h and UIImageView+AnimationCompletion.m files in project and them import UIImageView+AnimationCompletion.h file where you want to use this..
For eg.
NSMutableArray *imagesArray = [[NSMutableArray alloc] init];
for(int i = 10001 ; i<= 10010 ; i++)
[imagesArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]]];
self.animatedImageView.animationImages = imagesArray;
self.animatedImageView.animationDuration = 2.0f;
self.animatedImageView.animationRepeatCount = 3;
[self.animatedImageView startAnimatingWithCompletionBlock:^(BOOL success){
NSLog(@"Animation Completed",);}];
Solution 3
There is no way to do this precisely with UIImageView. Using a delay will work most of the time, but there can be some lag after startAnimating is called before the animation happens on screen so its not precise. Rather than using UIImageView for this animation try using a CAKeyframeAnimation which will call a delegate method when the animation is finished. Something along these lines:
NSArray * imageArray = [[NSArray alloc] initWithObjects:
(id)[UIImage imageNamed:@"HowTo1.png"].CGImage,
(id)[UIImage imageNamed:@"HowTo2.png"].CGImage,
nil];
UIImageView * instructions = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//create animation
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
[anim setKeyPath:@"contents"];
[anim setValues:imageArray];
[anim setRepeatCount:1];
[anim setDuration:1];
anim.delegate = self; // delegate animationDidStop method will be called
CALayer *myLayer = instructions.layer;
[myLayer addAnimation:anim forKey:nil];
Then just implement the animationDidStop delegate method
Solution 4
With this method you avoid timers to fire while the imageView is still animating due to slow image loading.
You could use both performSelector: withObject: afterDelay:
and GCD in this way:
[self performSelector:@selector(didFinishAnimatingImageView:)
withObject:imageView
afterDelay:imageView.animationDuration];
/!\ self.imageView.animationDuration
has to bet configured before startAnimating
, otherwise it will be 0
Than if -(void)didFinishAnimatingImageView:
create a background queue, perform a check on the isAnimating
property, than execute the rest on the main queue
- (void)didFinishAnimatingImageView:(UIImageView*)imageView
{
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.yourcompany.yourapp.checkDidFinishAnimatingImageView", 0);
dispatch_async(backgroundQueue, ^{
while (self.imageView.isAnimating)
NSLog(@"Is animating... Waiting...");
dispatch_async(dispatch_get_main_queue(), ^{
/* All the rest... */
});
});
}
Solution 5
Created Swift Version from GurPreet_Singh Answer (UIImageView+AnimationCompletion) I wasn't able to create a extension for UIImageView but I believe this is simple enough to use.
class AnimatedImageView: UIImageView, CAAnimationDelegate {
var completion: ((_ completed: Bool) -> Void)?
func startAnimate(completion: ((_ completed: Bool) -> Void)?) {
self.completion = completion
if let animationImages = animationImages {
let cgImages = animationImages.map({ $0.cgImage as AnyObject })
let animation = CAKeyframeAnimation(keyPath: "contents")
animation.values = cgImages
animation.repeatCount = Float(self.animationRepeatCount)
animation.duration = self.animationDuration
animation.delegate = self
self.layer.add(animation, forKey: nil)
} else {
self.completion?(false)
}
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
completion?(flag)
}
}
let imageView = AnimatedImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 135))
imageView.image = images.first
imageView.animationImages = images
imageView.animationDuration = 2
imageView.animationRepeatCount = 1
view.addSubview(imageView)
imageView.startAnimate { (completed) in
print("animation is done \(completed)")
imageView.image = images.last
}
Kevin_TA
Updated on June 05, 2022Comments
-
Kevin_TA almost 2 years
I have an array of images loaded into a UIImageView that I am animating through one cycle. After the images have been displayed, I would like a
@selector
to be called in order to dismiss the current view controller. The images are animated fine with this code:NSArray * imageArray = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"HowTo1.png"], [UIImage imageNamed:@"HowTo2.png"], nil]; UIImageView * instructions = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; instructions.animationImages = imageArray; [imageArray release]; instructions.animationDuration = 16.0; instructions.animationRepeatCount = 1; instructions.contentMode = UIViewContentModeBottomLeft; [instructions startAnimating]; [self.view addSubview:instructions]; [instructions release];
After the 16 seconds, I would like a method to be called. I looked into the
UIView
class methodsetAnimationDidStopSelector:
but I cannot get it to work with my current animation implementation. Any suggestions?Thanks.
-
Tieme over 11 yearsThis method seems to work fine, thanks rob! But i was wondering what would happen if for some reason the iPhone's frame-rate drop's a lot. Lets say from 30 to 15. In that case the animation wouldn't be finished playing when the dispatch timer run's out right?
-
rob mayoff over 11 yearsWhy do you think the frame rate dropping would make the animation take longer? Maybe the image view drops frames if it can't keep up.
-
Au Ris about 11 yearsThis is exactly the issue I am having with performSelector and delay. The array is too slow to load and loses time. Precision is lost. I need some other solution...
-
Matt Green over 10 yearsCan't add CGImage to array.
-
Matt Pearcy over 10 yearsTo get rid of the warning caused by adding CGImage to an array just cast it to id.
-
Matt Pearcy over 10 yearsAnswer edited to reflect above. See apples doc.
-
Adam Johns about 9 yearsI can't figure out how to use this in swift. After adding to bridging header it still doesn't work.
-
Javonne Martin over 5 yearsWorks like a charm only thing I added was
animation.calculationMode = .discrete
to disable the interpolation between the frames. It makes it look like a low fps gif. -
Semyon almost 5 yearsdispatch_after is inaccurate and can't be used in animation. Use CADisplayLink instead
-
rob mayoff almost 5 years
CADisplayLink
is good for syncing to individual display updates. This question is about detecting the end of an animation whose duration is not tied to the display's frame rate. However, if I were to try answering this question again today, I'd experiment with a wrapping theUIImageView
animation in aCATransaction
with a completion block.