当我按下按钮时,会出现带有标签的视图。然后我希望标签消失并重新出现5次(带动画),每次标签重新出现时都会显示不同的文字。 我似乎无法获得任何代码来动画UILabel并更改文本。我试过这个。但是,当我按下按钮时,循环和动画会立即发生。
持续时间如下: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)
}
答案 0 :(得分:1)
您正在更改duration
,但将delay
保留为0
(即立即开始)。在这些情况下,您可以反过来改变delay
并保持duration
不变。
但是考虑到你想要更改标签text
,我可能会改用计时器:
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
}
}
答案 1 :(得分:1)
也许是这样的:
func animate(alpha: CGFloat, start: Int, end: Int) {
infoViewMsgLbl.text = randomReward(real: Int(start/2)) // This retrives a String
UIView.animate(withDuration: 0.3, animations: {
self.infoViewMsgLbl.alpha = alpha
}, completion: { success in
if start + 1 <= end {
self.animate(alpha: alpha == 1.0 ? 0.0 : 1.0, start: start + 1, end: end)
}
})
}
用法:
animate(alpha:0.0, start: 0, end: 10) //would flash a total of 5 times
请注意,持续时间保持为0.3,因为它不会调用下一个循环,直到每增加0.3秒为止。