user4806509 user4806509 - 3 months ago 27
iOS Question

Starting fade animation from a specific point on an UIView in Swift

I’m having trouble with an animation fade-in and fade-out.

I have a simple set up, on the storyboard I have one

UIView
named
myView
.

What I want to do is fade-in
myView
when the user touches the screen, and fade-out
myView
when the user stops touching the screen. I can achieve that with the code below. The fade occurs over five seconds.

The problem however occurs when the user starts touching or stops touching the screen midway through a fade-in or fade-out animation.

For example, when the user stops touching the screen, instead of the fade-in animation gracefully stopping the
myView
fade-in at its current position and reversing with a fade-out animation, what actually occurs is
myView
alpha
jumps to
1.0
before beginning the fade out.

Question:


What changes to the code below need to be made to ensure that each new
animation, fade-in or fade-out, interrupts the current fade animation
occurring on
myView
and begins from the current
alpha
of the
previous fade animation?


Code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var myView: UIView!

override func viewDidLoad() {
super.viewDidLoad()
self.myView.alpha = 0
}

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

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
UIView.animateWithDuration(5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.myView.alpha = 1
}, completion: nil)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
UIView.animateWithDuration(5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.myView.alpha = 0
}, completion: nil)
}

}

Answer

The problem is that your touchesEnded animation interrupts your touchesBegan animation, causing the touchesBegan animation to be removed and revealing for an instant that you have set the alpha to 1.

To prevent this, include in your options: the .beginFromCurrentState option.