UIProgressView和定期刷新(Swift)



我需要解析相当多的文本,并希望在此过程中向用户提供一些反馈。

环境是Swift,虽然我确实在Obj-C中看到了一些代码([self-performSelector:@selector(…..)),但它没有多大意义。如果我知道如何将其嵌入Swift方法中,我会的。

我可以用一个可重复的小案例来总结这个问题,这个案例给出了相同的结果。即在循环中,增加一个值,显示进度并返回直到完成。显然,进度不会显示,因为iOS会等到循环完成后再刷新屏幕。

这确实有道理,所以我希望在继续处理之前,每隔不同的时间中断处理(即循环)并刷新进度条。

我当前的代码如下:

@IBAction func goButton(sender: UIButton) {
currentCounter = 0
target = textTarget.text.toInt()!
step = textStep.text.toInt()!
updateProgressBar()
while currentCounter < target {
currentCounter += step
updateProgressBar()
}
}
func updateProgressBar() {
var percentage = Float(currentCounter) / Float(target) * 100
progressPercentage.text = "(percentage) %"
println("progress = (percentage)")
progressBar.setProgress(percentage, animated: false)
}

我看到了以下内容:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// do some task here... 
}
dispatch_async(dispatch_get_main_queue()) {
// do another task here...
}

我该如何使用这种方法(如果相关的话),如果我这样做了,处理和刷新调用会在哪里出现?

Jon

GCD(Grand Central Dispatch)无疑是更好的选择。它使用起来简单、强大、直观,尽管语法一开始可能会提出其他建议。

在做耗时的工作时更新UI的方法的要点总是这样的:

  1. 您的应用程序正在主队列中运行
  2. 在某些情况下,您想做一些耗时的工作,所以将这些工作发送到主队列之外的某个队列。将dispatch_async与主队列以外的队列一起使用(有一些内置队列可以用于此操作,也可以创建自己的队列)
  3. 在您想要更新UI的耗时工作中UI应该始终在主队列中更新,因此在这项耗时的工作中,您可以执行另一个dispatch_async,这次使用主队列(有一种方法可以访问主队列)
  4. 在内部dispatch_async中,您可以更新UI

关于在Swift环境中使用GCD的良好而全面的教程,请查看以下内容。

下面是一个更新的答案,我认为其他人将从该模式中受益:

@IBAction func goButton(sender: UIButton) {
target = textTarget.text.toInt()!
step = textStep.text.toInt()!
currentCounter = 0
updateProgressBar()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.doTimeConsumingWork()
}
}
func doTimeConsumingWork() {
while currentCounter < target {
currentCounter += step
percentage = Float(currentCounter) / Float(target) * 100
if (percentage > 0.0) && (percentage % 10.0) == 0.0 {
// This is the important bit :)
// I chose to do this synchronously (not async) since progress updating can actually be done quite a while after the time consuming work is over
dispatch_sync(dispatch_get_main_queue()) {
self.updateProgressBar()
}
}
}
println("Finished doing time consuming work")
}
func updateProgressBar() {
progressPercentage.text = "(percentage) %"
println("target = (target), step = (step) progress = (percentage)")
progressBar.setProgress(percentage / 100.0, animated: false)
}

最新更新