基本上我想创建一个 UIProgressView 在 3 秒内从 0.0(空)变为 1.0(满)。谁能指出我在 UIProgressView 中快速使用 NSTimer 的正确方向?
问问题
1586 次
3 回答
1
如果有人对这里感兴趣的是 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!")
}
于 2020-03-11T17:22:08.723 回答
0
声明属性:
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 在主线程中更新。如果没有必要,请随意删除它。)
于 2015-07-15T13:01:16.053 回答
0
在搜索了一个并遇到了这个问题后,我创建了自己的解决方案。
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()
}
}
}
}
于 2016-04-13T07:25:42.440 回答