Andy
Andy

Reputation: 179

Swift - Animation not working when switch view and back

I notice that when I switch to another view and then back to the main view, my blinking animation stopped working. A tap brings it to another view and a button brings it back to the main view. Here is my code:

For blinking animation:

import Foundation

import UIKit

extension UILabel {

func startBlink() {
    UIView.animate(withDuration: 0.8,
                   delay:0.0,
                   options:[.autoreverse, .repeat],
                   animations: {
                    self.alpha = 0

    }, completion: nil)
}

func stopBlink() {
    alpha = 1
    layer.removeAllAnimations()
}

}

Action for button to bring the it back to main screen:

@IBAction func mainMenuTapped(_ sender: Any) {

    performSegue(withIdentifier: "EndToMain", sender: self)

}

Main view code that start the blinking animation:

@IBOutlet weak var tapToPlayLabel: UILabel!




override func viewDidLoad() {
    super.viewDidLoad()



    tapToPlayLabel.startBlink()

}

Thanks for all the help!

Upvotes: 0

Views: 2255

Answers (2)

Purnendu roy
Purnendu roy

Reputation: 818

Most of the times UIView animation custom methods won't work when switching back to the original view. To make that work you need to assign some initial values related to that Custom animation.

Here is the example:

 override func viewDidAppear(_ animated: Bool) {
     super.viewDidAppear(animated)
     self.tapToPlayLabel.alpa = 20
     self.tapToPlayLabel.layoutIfNeeded()
     self.tapToPlayLabel.startBlink()
}

Upvotes: 0

Barns
Barns

Reputation: 4848

Take a look at the iOS UIView lifecycle to understand when which methods are called.

Take tapToPlayLabel.startBlink() out of viewDidLoad and put it into either viewDidAppear or viewWillAppear like this:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tapToPlayLabel.startBlink()
}

Upvotes: 1

Related Questions