Swift Infinite Fade in and Out Loop
Asked Answered
S

7

9

How can I make a effect in swift similar to this: enter image description here

I want the animation to loop forever.

Subtangent answered 18/6, 2016 at 3:40 Comment(0)
E
16

For iOS

UIViewAnimationOptions set provides different handy options to achieve a combination of beautiful and complex animations. For your particular scenario you will require two of the options.

UIViewAnimationOptions.Repeat
UIViewAnimationOptions.AutoReverse

Check out the code below for implementation.

Code:

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        view.backgroundColor = UIColor.blueColor()
        self.view.addSubview(view)

        UIView.animateWithDuration(1, 
        delay: 0, 
        options: [UIViewAnimationOptions.Autoreverse, UIViewAnimationOptions.Repeat], 
        animations: {
              view.backgroundColor = UIColor.clearColor()
          }, 
        completion: nil)
    }

}

Explanation: I have created a view with a specific frame for demo purpose.

The part you are interested in is the UIView.animateWithDuration method. Notice that I have provided an array [UIViewAnimationOptions.AutoReverse, UIViewAnimationOptions.Repeat] in the options parameter.

These two options are enough to achieve a smooth and forever looping animation like below. https://s3.amazonaws.com/uploads.hipchat.com/37040/1764070/6Iow7n7WiWf6Naz/autoReverse.gif

If you don't want to reverse the animation, just remove UIViewAnimationOptions.AutoReverse from the array in the options parameter. You will get an animation like this. https://s3.amazonaws.com/uploads.hipchat.com/37040/1764070/8fyRUlzqNHSQI47/noreverse.gif

Exstipulate answered 18/6, 2016 at 4:53 Comment(6)
How do I make a label do this?Subtangent
UILabel is the subclass of UIView. Therefore its the same process. So instead of the view that I have used in the code, replace it with a UILabel.Exstipulate
Can you do that for me? I have a little trouble understanding this code.Subtangent
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) label.backgroundColor = UIColor.blueColor() self.view.addSubview(label) UIView.animateWithDuration(1, delay: 0, options: [UIViewAnimationOptions.Autoreverse, UIViewAnimationOptions.Repeat], animations: { label.backgroundColor = UIColor.clearColor() }, completion: nil)Exstipulate
Copy and paste above code in you viewDidLoad method and watch it work. Also check out my edited answer. :)Exstipulate
Fantastic, great answer. Now my question is, how do I stop it?Karalee
P
12

For iOS

let viewSquare be the name of the blue square in your question.

UIView.animate(withDuration: 0.5, delay: 0, options: [.repeat,.autoreverse], animations: {
            viewSquare.alpha = 0.0
        }, completion: nil)
Pule answered 12/1, 2017 at 11:18 Comment(0)
E
3

Swift 5.1

let duration = 0.5


func fadeIn(finished: Bool) {
    UIView.animate(withDuration: self.duration, delay: 0,
                   options: [.curveEaseInOut],
                   animations: { self.tftMap.alpha = 1 }, completion: self.fadeOut)
}

func fadeOut(finished: Bool) {
    UIView.animate(withDuration: self.duration, delay: 0,
                   options: [.curveEaseInOut],
                   animations: { self.tftMap.alpha = 0 }, completion: self.fadeIn)
}
Endarch answered 24/1, 2020 at 19:15 Comment(0)
A
2

I assume you are programming for iOS.

Play around with the duration to see what suits you best:

class ViewController: UIViewController {
    @IBOutlet weak var myView: UIView!
    let duration = 0.5

    override func viewDidLoad() {
        super.viewDidLoad()
        self.fadeOut(true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func fadeIn(finished: Bool) {
        UIView.animateWithDuration(self.duration, delay: 0, options: [.CurveEaseInOut], animations: { self.myView.alpha = 1 } , completion: self.fadeOut)
    }

    func fadeOut(finished: Bool) {
        UIView.animateWithDuration(self.duration, delay: 0, options: [.CurveEaseInOut], animations: { self.myView.alpha = 0 } , completion: self.fadeIn)
    }
}
Ava answered 18/6, 2016 at 4:19 Comment(2)
You might want to check out the .Repeat and .Autoreverse animation options.Shirtmaker
How do I make a label do this?Subtangent
M
1

Swift 5

This worked well for me. I wanted to animate a continuous fade in and out of a label, which I placed inside the "cardHeaderView" UIView.

@IBOutlet weak var cardHeaderView: UIView!

Place this inside the "viewDidAppear". I went with a delay of zero so the animation would start right away.

fadeViewInThenOut(view: cardHeaderView, delay: 0)

Here is the function.

func fadeViewInThenOut(view : UIView, delay: TimeInterval) {

    let animationDuration = 1.5

    UIView.animate(withDuration: animationDuration, delay: delay, options: [UIView.AnimationOptions.autoreverse, UIView.AnimationOptions.repeat], animations: {
        view.alpha = 0
    }, completion: nil)

}
Mythopoeia answered 10/7, 2019 at 2:58 Comment(0)
C
1

Swift 5

  • Fade in 2 seconds
  • pause 2 seconds,
  • fade out 2 seconds Repeat
func startAnimation() {
     UIView.animateKeyframes(withDuration: 6.0,
                                    delay: 0,
                                    options: [.repeat, .autoreverse, .calculationModeLinear]) {
        UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.165) { [weak self] in
            self?.view1.alpha = 0.0
        }
        UIView.addKeyframe(withRelativeStartTime: 0.165, relativeDuration: 0.165) { [weak self] in
            self?.view2.alpha = 1.0
        }
        UIView.addKeyframe(withRelativeStartTime: 0.66, relativeDuration: 0.165) { [weak self] in
            self?.view2.alpha = 0.0
        }
        UIView.addKeyframe(withRelativeStartTime: 0.825, relativeDuration: 0.165) { [weak self] in
            self?.view1.alpha = 1.0
        }
    }
}

Please note that when your animation is at Alpha == 0.0 the item is not interactable! You will have to add to .allowUserInteraction as an option

Cultivar answered 31/10, 2022 at 18:35 Comment(0)
M
0

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

###First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
       let flash = CABasicAnimation(keyPath: AnimationKeyPath.opacity.rawValue)
       flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

###How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
Mirza answered 12/9, 2018 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.