swift 中 forEach 循环的进度条

Progress Bar on forEach loop in swift

如何测量 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)
    }
}

您可以使用 ProgressView 作为简单的进度条。您可以像任何其他视图一样将它添加到视图控制器(作为@IBOutlet weak var)。在 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
    }
}

您可以使用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 进度达到最大值时,您可以执行自己的操作

这样做:

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