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()
}
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()
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.