我在一个标签(存储在'profile / uid'下)的firebase数据库中调用用户“Weight”,它有两个类别“kg”和“lbs”。我希望标签能够以kg为单位显示用户的体重,然后逐渐淡出到lbs,然后再重新回到kg,等等。到目前为止,我已经编写了以下代码,这些代码在lbs中不断淡出和减轻重量,我不确定如果lbs淡出,如何让它以kg为单位显示重量:
func weight() {
let userRf = self.firDatabaseRef.child("profile").child("\(User!.uid)").observe(FIRDataEventType.value, with: { (snapshot) in
if snapshot.exists() {
if let weight = snapshot.childSnapshot(forPath: "weight").value as? [String: AnyObject] {
if let kg = weight["kg"] as? Float, let lbs = weight["lbs"] as? Int {
let animation: CATransition = CATransition()
animation.duration = 2.0
animation.type = kCATransitionFade
animation.repeatDuration = .infinity
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.displayWeight.layer.add(animation, forKey: "changeTextTransition")
self.displayWeight.text = "\(lbs) lbs"
}
}
}
}
}
答案 0 :(得分:1)
一种方法是使用重复的UIVIew
动画和Timer
:
// set up some helpful constants
let kgsText = "\(kgs) kgs"
let lbsText = "\(lbs) lbs"
let fadeDuration = 2.0
// keep track of which unit is being displayed
var isDisplayingKgs = true
// animate the fade in and out, repeating
UIView.animate(withDuration: fadeDuration, delay: 0, options: [.autoreverse, .repeat], animations: {
label.alpha = 0
}, completion: nil)
// start the timer to switch the text after a short delay
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + fadeDuration) {
self.displayWeight.text = lbsText
isDisplayingKgs = false
Timer.scheduledTimer(withTimeInterval: fadeDuration * 2, repeats: true, block: { timer in
self.displayWeight.text = isDisplayingKgs ? lbsText : kgsText
isDisplayingKgs = !isDisplayingKgs
})
}
这假设您的标签开始可见(alpha = 1)。调度延迟是为了确保第一次转换发生在标签第一次淡出时,但在定时器启动之前。
以下是动画的实际效果: