Reputation: 125
I am trying to animate a UILabel to go from 0% to (insert number)%, and show each number in between in a duration of 1 second..
I have failed until now and I am going crazy :-)
I haven't even made it to the part where I can set the duration yet.. What I have done so far (and failed at) is this:
var current: Int = Int(0.0 * 100)
let endValue: Int = Int(toValue * 100)
if current < endValue {
self.progressLabel.text = "\(current)%"
current += Int(0.01 * 100)
}
The toValue
is a Double that it is receiving when the function is called.
Any help would be great!
EDIT:
I made it show the correct endValue
in the uilabel using this code instead and moving var current...
up before the viewDidLoad. The problem is now that it is not showing the numbers in between the current and the endValue in the progressLabel.text
..
while current <= endValue {
self.progressLabel.text = "\(current)%"
current = current + Int(0.01 * 100)
}
Upvotes: 1
Views: 1517
Reputation: 36610
Here is a function that does not rely on timers, instead using the DispatchQueue
asyncAfter
method from GCD.
func updateCounter(currentValue: Int, toValue: Double) {
if currentValue <= Int(toValue * 100) {
progressLabel.text = "\(currentValue)%"
let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
self.updateCounter(currentValue: currentValue + 1, toValue: toValue)
})
}
}
Calling it with this will produce a count from 0-10:
updateCounter(currentValue: 0, toValue: 0.1)
Upvotes: 3
Reputation: 75
The problem you have now in your recently updated code is that your program will not update the UILabel every time current is changed. The while loop will continue until current reaches is final value, then your UILabel will be updated once.
What would probably help you is using timers, as referenced in this answer:
How to make a countdown with NSTimer on Swift
Make a method that increments the UILabel's current value by one, then use the timer to call that method once every second.
Upvotes: 0