我的应用程序有一个导入功能,它获取来自另一个 ViewController 的字符串数据并使用展开转场传递它。在目标 ViewController 中,有一个 ProgressView 添加到了 AlertView,它应该针对字符串的每个导入组件进行更新,但进度条永远不会更新。
这是目标 ViewController:
import UIKit
class MoviesViewController: UITableViewController {
var progressView: UIProgressView!
[...]
@IBAction func addImportedMovies(_ segue: UIStoryboardSegue) {
if let importViewController = segue.source as? ImportViewController, let importedMovielist = importViewController.movies {
importedMovies = importedMovielist.reversed()
if importedMovies != [] {
self.parent?.dismiss(animated: true, completion: nil)
let alertView = UIAlertController(title: "Please wait", message: "Data is being processed...", preferredStyle: .alert)
present(alertView, animated: true, completion: { [self] in
let margin:CGFloat = 8.0
let rect = CGRect(x: margin, y: 72.0, width: alertView.view.frame.width - margin * 2.0 , height: 2.0)
progressView = UIProgressView(frame: rect)
progressView.tintColor = view.tintColor
alertView.view.addSubview(progressView)
progressView.isHidden = false
DispatchQueue.main.async { [self] in
progressView.progress = 0.0/Float(importedMovies.count)
for (i, movie) in importedMovies.enumerated() {
progressView.progress = Float(i+1)/Float(importedMovies.count)
print(progressView.progress)
[...updating DataSource and TableView]
}
[...]
alertView.dismiss(animated: true, completion: nil)
importedMovies = []
}
})
}
}
}
}
我尝试使用 DispatchQueue.global,将代码移至 ViewWillAppear 以及我在类似线程中看到的各种其他更改,但没有成功。
试试这个:
@IBAction func addImportedMovies(_ segue: UIStoryboardSegue) {
if let importViewController = segue.source as? ImportViewController, let importedMovielist = importViewController.movies {
importedMovies = importedMovielist.reversed()
if !importedMovies.isEmpty {
self.parent?.dismiss(animated: true, completion: nil)
// Create an alert controller
let alertView = UIAlertController(title: "Please wait", message: "Data is being processed...", preferredStyle: .alert)
// Add a progress view to the alert controller
let progressView = UIProgressView(progressViewStyle: .default)
alertView.view.addSubview(progressView)
// Present the alert controller
present(alertView, animated: true, completion: { [self] in
// Perform UI updates on the main thread
DispatchQueue.main.async { [self] in
progressView.progress = 0.0
// Iterate through importedMovies and update progress view
for (i, movie) in importedMovies.enumerated() {
progressView.progress = Float(i + 1) / Float(importedMovies.count)
print(progressView.progress)
// [...updating DataSource and TableView]
}
// Other updates...
alertView.dismiss(animated: true, completion: nil)
importedMovies = []
}
})
}
}
}