我的视图中有3个标签和一个UIButton。按下UIButton后,一些函数正在执行,我希望它们执行以下操作:
图1完成下载后,标签1将被更新,图2完成后,标签2将被更新,等等。
问题是:我的视图,所以我的标签,所有功能解决后都会立即更新...
我读到了异步任务 - 但在我的理解中我不需要它,因为我不介意用户是否只要执行所有函数就不能单击任何按钮,我想要的只是视图(标签)在执行功能时更新,不仅在完成所有操作后...
这是我的代码:
@IBAction func ButtonLoadPictures(_ sender: UIButton) {
// Picture1
downloadImage()
LabelResult1.text = "Ready"
// Picture2
downloadImage()
LabelResult2.text = "Ready"
// Picture3
downloadImage()
LabelResult3.text = "Ready"
}
编辑:
因为我被问到downloadImage()中的代码: downloadImage只是我在这个地方有很多功能的占位符。但根据我的理解,代码具体是什么并不重要。如果是的话,我已经为downloadImage()添加了一个例子。问题是我不想在执行所有函数后立即更新我的标签,但是在每次“donwnloadImage()”之后
func downloadImage(){
guard let myURL = URL(string: myLink) else {
print("Error: \(myLink) doesn't seem to be a valid URL")
return
}
do {
myLinkHTMLcontent = try String(contentsOf: myURL, encoding: .ascii)
print(myLinkHTMLcontent)
} catch let error {
print("Error: \(error)")
}
答案 0 :(得分:0)
在这种情况下我选择的路径是逻辑中的异步任务,并使用完成处理程序,如下所示:
IBAction func ButtonLoadPictures(_ sender: UIButton) {
// Picture1
downloadImage(){ result in
self.LabelResult1.text = result
}
// Picture2
downloadImage(){ result in
self.LabelResult2.text = result
}
// Picture3
downloadImage(){ result in
self.LabelResult3.text = result
}
}
func downloadImage(completion: @escaping(String) -> ()){
// all your logic
completion("ready")
}