创建一个 UIProgressView 在 3 秒内从 0.0(空)变为 1.0(满)

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

基本上我想创建一个 UIProgressView 在 3 秒内从 0.0(空)变为 1.0(满)。谁能指出我在 swift 和 UIProgressView 中使用 NSTimer 的正确方向?

声明属性:

var time = 0.0
var timer: NSTimer

初始化定时器:

timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)

实现setProgress函数:

func setProgress() {
    time += 0.1
    dispatch_async(dispatch_get_main_queue(), {
        progressView.progress = time / 3 
    })
    if time >= 3 {
        timer.invalidate()
    }
}

(我不是 100% 确定是否需要调度块,以确保 UI 在主线程中更新。如果不需要,请随意删除它。)

我在搜索一个解决方案并遇到这个问题后创建了自己的解决方案。

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()
            }
        }
    }
}

如果有人对这里感兴趣是 Swift 5 工作版本:

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!()
                }
            }
        }
    }
}

用法:

// Will fill the progress bar in 70 seconds
self.progressBar.setAnimatedProgress(duration: 70) {
    print("Done!")
}