如何测量forEach
循环的进度并将其显示在进度栏中?
我将旋转垂直图像以使其变为水平。每次要转换的图像数量都不同。
这是我要转换的图像的正常工作,我只需要一种向用户显示进度的方法:
func rotateandSave(files: [URL]) {
files.forEach { file in
let path = file
let image = NSImage(contentsOf: path)
let rotatedImage = image?.rotated(by: rotateAngle)
saveImage(image: rotatedImage!, destination: path)
}
}
答案 0 :(得分:0)
您可以将ProgressView用于简单的进度栏。您可以像其他任何视图一样将其添加到视图控制器中(作为@IBOutlet弱变量)。在viewDidLoad()中将进度设置为0,以使栏开始为空。
ProgressView的进度设置在0.0-1.0的范围内,可以设置动画选项(我想您希望这样做)。要更新ProgressView,您可以修改现有功能:
@IBOutlet weak var progressView: UIProgressView!
...
func rotateandSave(files: [URL]) {
let numFiles = files.count
let fileNum = 0
files.forEach { file in
let path = file
let image = NSImage(contentsOf: path)
let rotatedImage = image?.rotated(by: rotateAngle)
saveImage(image: rotatedImage!, destination: path)
progressBar.setProgress(Double(fileNum)/Double(numFiles), true)
fileNum += 1
}
}
答案 1 :(得分:0)
您可以使用ProgressView
显示进度栏。您可以将其添加到您的控制器中,如下所示:
@IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
progressView.progress = 0.0
}
func rotateandSave(files: [URL]) {
var numberOfFile = files.count
var fileCounter = 0
files.forEach { file in
let path = file
let image = NSImage(contentsOf: path)
let rotatedImage = image?.rotated(by: rotateAngle)
saveImage(image: rotatedImage!, destination: path)
fileCounter + =1
let progress = (Double(fileCounter)/Double(numberOfFile))
progressView.setProgress(progress, animated: true)
}
}
当您的progressView的进度此时达到最大时,您可以执行自己的操作
答案 2 :(得分:0)
执行此操作:
func rotateandSave(files: [URL]) {
DispatchQueue.global(qos: .utility).async {
files.forEach { file in
let path = file
let image = NSImage(contentsOf: path)
let rotatedImage = image?.imageRotated(by: 90)
saveImage(image: rotatedImage!, destination: path)
DispatchQueue.main.async {
self.progressBar.increment(by: 1)
}
}
}