简体   繁体   中英

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

}

}

You can achieve your desired effect with one repeating animation. Pass .Autoreverse | .Repeat .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

By calling the fadeOut() immediately after fadeIn(), the system is technically starting the second animation immediately, the first step of which is to delay. In order to start the second animation, it finishes the first animation immediately and moves on.

Try calling fadeOut() from inside fadeIn() once the animation completes, then you can call fadeIn() as many times as you'd like, or put it in a loop to keep it running.

Courtesy of Angela, this code creates a flashing ring with variable period. Many thanks.

func fadeInOutSphere() {

    greenRingSphere.alpha = 0.2

    UIImageView.animateWithDuration(3.0, delay: 0.0, options: .Autoreverse | .Repeat, animations: {

        self.greenRingSphere.alpha = 1

        }, completion: nil)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM