Ios 从长任务更新加载栏

Ios 从长任务更新加载栏,ios,swift,loading,Ios,Swift,Loading,我正在尝试制作一个加载条,因为我完成一个长函数可能需要几秒钟。但是,我不知道如何才能知道我在函数执行方面走了多远,以及如何触发UI中的更改。下面是我所拥有的工作正常,但我不会完全按照期望的方式行事。有什么建议吗 func build(_ sender: UIButton) { let myMutableString = NSMutableAttributedString(string: "Compiling Latest Clean Build", attributes: [NSFon

我正在尝试制作一个加载条,因为我完成一个长函数可能需要几秒钟。但是,我不知道如何才能知道我在函数执行方面走了多远,以及如何触发UI中的更改。下面是我所拥有的工作正常,但我不会完全按照期望的方式行事。有什么建议吗

func build(_ sender: UIButton) {

    let myMutableString = NSMutableAttributedString(string: "Compiling Latest Clean Build", attributes: [NSFontAttributeName: buildLbl.font])
    buildLbl.attributedText = myMutableString

    let greenStrip = UIView()
    greenStrip.backgroundColor = Colors().green
    greenStrip.frame = CGRect(x: 0, y: buildStatus.frame.height - 2.5, width: 10, height: 2.5)
    buildStatus.addSubview(greenStrip)

    UIView.animate(withDuration: 2.0, animations: {
        // compile can take a while
        compile(structureContent: structuredContent)
        greenStrip.frame = CGRect(x: 0, y: self.buildStatus.frame.height - 2.5, width: self.buildStatus.frame.width, height: 2.5)

    }, completion: {
        (value: Bool) in

        greenStrip.removeFromSuperview()
        let dvc : PreviewViewController = self.storyboard?.instantiateViewController(withIdentifier: "PreviewViewController") as! PreviewViewController
        self.navigationController?.pushViewController(dvc, animated: false)

    })

}

您希望跟踪
compile()
函数在数据结构中循环并执行操作的进度。首先,您需要一个来自
compile()
函数的委托函数,该函数以百分比形式报告进度,以便以后可以在UI上显示进度。您可以找到一个关于委托的完整教程,您的协议将类似于

protocol ProgressDelegate: class {
    func didFinishTask(progress: Double)
}
func compile(){
    ...
    let totalJobs = jobs.count
    let counter = 0.0
    for eachJob in jobs {
        counter += 1.0
        ...
        didFinishTask(progress: counter/totalJobs)
    }
}
下面是一个报告进度的示例方法。在
compile()
函数的开头,您希望从数据结构中获得一个计数作为总作业数。然后在for循环的每一轮中,将当前循环计数除以总计数,然后按代理报告此进度。所以你的代码看起来像

protocol ProgressDelegate: class {
    func didFinishTask(progress: Double)
}
func compile(){
    ...
    let totalJobs = jobs.count
    let counter = 0.0
    for eachJob in jobs {
        counter += 1.0
        ...
        didFinishTask(progress: counter/totalJobs)
    }
}
最后,在接收此委托的UI视图控制器中。将UI base one更新为完成任务的百分比

func didFinishTask(progress: Double){
    // set up status bar here
}

如果我知道你的长功能,我可以帮你。你能简单地告诉我们你的长函数在做什么以及你是如何实现它的吗?
compile()
函数主要是写文件。它还保存图像和声音。它通过数据结构进行迭代,并写入文件或保存内容。