Basically I want to create a UIProgressView to go from 0.0 (empty) to 1.0 (full) in 3 seconds. Could anyone point me in the right direction for using NSTimer in swift with UIProgressView?
Create a UIProgressView to go from 0.0 (empty) to 1.0 (full) in 3 seconds
2.1k Views Asked by dwinnbrown At
3
There are 3 best solutions below
6

Declare the properties:
var time = 0.0
var timer: NSTimer
Initialize the timer:
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)
Implement the setProgress function:
func setProgress() {
time += 0.1
dispatch_async(dispatch_get_main_queue(), {
progressView.progress = time / 3
})
if time >= 3 {
timer.invalidate()
}
}
(I'm not 100% sure if the dispatch block is necessary, to make sure the UI is updated in the main thread. Feel free to remove this if it isn't necessary.)
0

If anyone's interested here is a Swift 5 working version :
extension UIProgressView {
@available(iOS 10.0, *)
func setAnimatedProgress(progress: Float = 1, duration: Float = 1, completion: (() -> ())? = nil) {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
DispatchQueue.main.async {
let current = self.progress
self.setProgress(current+(1/duration), animated: true)
}
if self.progress >= progress {
timer.invalidate()
if completion != nil {
completion!()
}
}
}
}
}
Usage :
// Will fill the progress bar in 70 seconds
self.progressBar.setAnimatedProgress(duration: 70) {
print("Done!")
}
I created my own solution after searching for one and coming across this question.