james james - 1 month ago 5
iOS Question

How can I make an UILabel appear and disappear 5 times?

When I press a button, a view with a label appears. Then I want the label to disappear and reappear 5 times (with animation), each time the label reappears with different text.
I can't seem to get the any code to work to animate a UILabel and change the text. I have tried this. However, when I press the button, the loop and animations occur instantly.

The duration is a follows: 0.3, 0.6, 0.9, 1.2, 1.5

for i in 1...5 {

infoViewMsgLbl.text = randomReward(real: i) // This retrives a String

UIView.animate(withDuration: ((1.5/5)*Double(i)), delay: 0.0, options: .allowAnimatedContent, animations: {
self.infoViewMsgLbl.alpha = 0
}, completion: { finished in
UIView.animate(withDuration: ((1.5/5)*Double(i)), animations: {
self.infoViewMsgLbl.alpha = 1
})
})

print("in the loop: ", i)
}

Rob Rob
Answer

You are changing duration, but leaving delay as 0 (i.e. start immediately). In these cases, you might do it the other way around, changing delay and leaving duration unchanged.

But given that you want to change the label text, I might use a timer instead:

var index = 1
Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { [weak self] timer in
    self?.infoViewMsgLbl.alpha = 0
    self?.infoViewMsgLbl.text = self?.randomReward(real: index)
    index += 1
    if index > 5 { timer.invalidate() }
    UIView.animate(withDuration: 0.3) {
        self?.infoViewMsgLbl.alpha = 1
    }
}