Search code examples
iosimageswiftanimationfade

How do I get this fade animation to work?


I'm trying to set up a simple pulsating ring that will highlight a button, to prompt the user to the recommended choice. I made simple fadeIn() and fadeOut() functions, set a delay in the fadeOut(), so that it will trigger as the fadeIn() completes...or at least that's what I intended. What results is, when the button is pressed, the ring instantly goes to alpha = 1, then delays for 2 seconds, and then fades over 2 seconds. Once I have a cycle working, I'd like to put it into a loop to keep it going while needed.

Either function will work as intended, if executed alone. I found another thread that deals with simple fadeIn or fadeOut, but not both together.

I'm sure the code is doing exactly what I'm telling it do, but I can't figure out why it's not working. Can someone point to my mistake? Thanks.

@IBOutlet weak var greenRing: UIImageView!

@IBAction func buttonPressed(sender: AnyObject)

    {
        fadeIn()

        fadeOut()
    }

func fadeIn() {

    UIImageView.animateWithDuration(2.0, animations: {

        self.greenRing.alpha = 1

        })

}

func fadeOut() {

    UIImageView.animateWithDuration(2.0, delay: 2.0, options: nil, animations: {

        self.greenRing.alpha = 0

        }, completion: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()

    greenRing.alpha = 0

}

}


Solution

  • You can achieve your desired effect with one repeating animation. Pass .Autoreverse | .Repeat as the options: to animateWithDuration and it will automatically reverse and repeat the fadeIn.

    When the button is pressed, you can stop the animation by calling greenRing.layer.removeAllAnimations()

    The animation will also likely look nicer if you also add the option UIViewAnimationOption.CurveEaseInOut. So:

    .Autoreverse | .Repeat | .CurveEaseInOut