Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show and Fade UIImageView after 2 Seconds

I am working on a notification system in my iPhone game and want an image to pop up on the screen and automatically fade after 2 seconds.

  1. User clicks a button that calls the method "popupImage"
  2. An image appears on the screen in a designated spot, it doesn't need to fade in
  3. The image fades out by itself after being on the screen for 2 seconds.

Is there any way of doing this? Thanks ahead of time.

like image 594
felix_xiao Avatar asked Sep 17 '12 21:09

felix_xiao


3 Answers

Use UIView dedicated methods for that.

So imagine you already have your UIImageView ready, already created and added to the main view, but simply hidden. Your method simply need to make it visible, and start an animation 2 seconds later to fade it out, by animating its "alpha" property from 1.0 to 0.0 (during a 0.5s animation):

-(IBAction)popupImage
{
    imageView.hidden = NO;
    imageView.alpha = 1.0f;
    // Then fades it away after 2 seconds (the cross-fade animation will take 0.5s)
    [UIView animateWithDuration:0.5 delay:2.0 options:0 animations:^{
         // Animate the alpha value of your imageView from 1.0 to 0.0 here
         imageView.alpha = 0.0f;
     } completion:^(BOOL finished) {
         // Once the animation is completed and the alpha has gone to 0.0, hide the view for good
         imageView.hidden = YES;
     }];
}

Simple as that!

like image 158
AliSoftware Avatar answered Nov 14 '22 12:11

AliSoftware


Swift 2

self.overlay.hidden = false
UIView.animateWithDuration(2, delay: 5, options: UIViewAnimationOptions.TransitionFlipFromTop, animations: {
    self.overlay.alpha = 0
}, completion: { finished in
    self.overlay.hidden = true
})

Swift 3, 4, 5

self.overlay.isHidden = false
UIView.animate(withDuration: 2, delay: 5, options: UIView.AnimationOptions.transitionFlipFromTop, animations: {
    self.overlay.alpha = 0
}, completion: { finished in
    self.overlay.isHidden = true
})

Where overlay is the outlet for my image.

like image 12
Joseph Selvaraj Avatar answered Nov 14 '22 11:11

Joseph Selvaraj


Swift 3 version of @AliSoftware's answer

imageView.isHidden = false
imageView.alpha = 1.0

UIView.animate(withDuration: 0.5, delay: 2.0, options: [], animations: {

            self.imageView.alpha = 0.0

        }) { (finished: Bool) in

            self.imageView.isHidden = true
        }
like image 3
iUser Avatar answered Nov 14 '22 12:11

iUser