How do I change the text of a UILabel between each animation of animateWithDuration with repeat?

痞子三分冷 提交于 2021-01-28 19:34:55

问题


I have an Array words containing ["alice", "bob", "charles"] and a UILabel label. I want label to repeatedly fade in and out, with a different word from words each time. If I put the text-changing code inside the animations block, it doesn’t execute, even though the fading works as expected (the completion block is run only when something stops the repetition):

label.alpha = 0

UIView.animateWithDuration(4, delay: 0, options: .Autoreverse | .Repeat, animations: {
    self.label.text = nextWord()
    self.label.alpha = 1
}, completion: {_ in
    NSLog("Completed animation")
})

What’s a good way to fix this? Thanks.


回答1:


surely not the most elegant but working solution:

@IBOutlet weak var label: UILabel!

let words = ["Is", "this", "what", "you", "want?"]
var currentIndex = -1

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    showNextWord()
}

func showNextWord() {
    if currentIndex == words.count - 1 {
        currentIndex = -1
    }

    UIView.animateWithDuration(1, delay: 1, options: UIViewAnimationOptions(0), animations: { () -> Void in
        self.label.alpha = 0.0
    }) { (_) -> Void in
        self.label.text = self.words[++self.currentIndex]
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.label.alpha = 1.0
            }, completion: { (_) -> Void in
                self.showNextWord()
        })
    }
}



回答2:


You could construct this as a keyframe animation. That way, you can chain three animations together (one for each word) and repeat that entire chain.

Alternatively (this is what I would probably do), put one animation into a method of its own, and in the completion block, add a short delay and call the method - thus creating a perpetual loop. The loop creates the repetition, but each animation is just one animation, so now you can progress through the array on successive calls. So the structure (pseudo-code) would look like this:

func animate() {
    let opts = UIViewAnimationOptions.Autoreverse
    UIView.animateWithDuration(1, delay: 0, options: opts, animations: {
       // animate one fade in and out
    }, completion: {
       _ in
       delay(0.1) {
           // set the next text
           self.animate() // recurse after delay
       }
    })
}


来源:https://stackoverflow.com/questions/29856947/how-do-i-change-the-text-of-a-uilabel-between-each-animation-of-animatewithdurat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!