reinho14
reinho14

Reputation: 43

Animated UILabel disappears when returning from background

I have UILabel that fades in and out repeatedly, but when app returns from background the text disappears.

I tried the following, but it didn't work,

override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(fadeText), name: UIApplication.willEnterForegroundNotification, object: nil)
}
    func fadeInThenOut(label : UILabel, delay: TimeInterval) {

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

    }

@objc func fadeText() {
        fadeInThenOut(label: textLabel, delay: 0)
    }

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

        fadeText()

    }

Upvotes: 1

Views: 267

Answers (1)

Mumtaz Hussain
Mumtaz Hussain

Reputation: 1125

Change willEnterForegroundNotification to didBecomeActiveNotification like this:

NotificationCenter.default.addObserver(self, selector: #selector(fadeText), name: UIApplication.didBecomeActiveNotification, object: nil)

Then your selector should have an initial alpha value for self.view:

  @objc func fadeText() {
        self.view.alpha = 1
        fadeInThenOut(label: label, delay: 0)
    }

Now you don't need that code in ViewDidAppear.

Your whole code should look like this:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(fadeText), name: UIApplication.didBecomeActiveNotification, object: nil)
}

func fadeInThenOut(label : UILabel, delay: TimeInterval) {
    UILabel.animate(withDuration: 2.0, delay: delay, options: [UILabel.AnimationOptions.autoreverse, UILabel.AnimationOptions.repeat], animations: {
        self.view.alpha = 0
    }, completion: { (finished: Bool) in
        print("done")
    })

}

@objc func fadeText() {
    self.view.alpha = 1
    fadeInThenOut(label: textLabel, delay: 0)
}

Updated: The above code animates self.view, not the textLabel. If you want to animate the label only then change self.view.alpha into self.textLabel.alpha inside both fadeInThenOut() and fadeText()

Upvotes: 3

Related Questions