Search code examples
iosswiftuiprogressviewuiprogressbar

Create a UIProgressView to go from 0.0 (empty) to 1.0 (full) in 3 seconds


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?


Solution

  • I created my own solution after searching for one and coming across this question.

    extension UIProgressView {
    
        func setAnimatedProgress(progress: Float,
            duration: NSTimeInterval = 1,
            delay: NSTimeInterval = 0,
            completion: () -> ()
        ) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
                sleep(UInt32(delay))
                dispatch_async(dispatch_get_main_queue()) {
                    self.layer.speed = Float(pow(duration, -1))
                    self.setProgress(progress, animated: true)
                }
                sleep(UInt32(duration))
                dispatch_async(dispatch_get_main_queue()) {
                    self.layer.speed = 1
                    completion()
                }
            }
        }
    }