使用 CAAnimation 无限旋转两个变量

Infinitely rotate two variables using CAAnimation

我正在从一个标签(存储在 'profile/uid' 下)中的 firebase 数据库中调用用户 "Weight",该标签有两个类别 "kg" 和 "lbs"。我希望标签能够以千克为单位显示用户的体重,然后淡出到磅,然后再次回到千克,依此类推。到目前为止,我已经编写了以下代码,它不断淡入和淡出以磅为单位的重量,我不确定如何让它在磅消失后显示以公斤为单位的重量:

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"

                }
            }
        }
    }

}

一种方法是使用重复的 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)。调度延迟是为了确保第一次转换发生在标签第一次淡出时,但在计时器开始之前。

动画效果如下: