[英]Return in Completion Block Swift
我執行KolodaView請訪問: https://github.com/Yalantis/Koloda 。 viewForCardAt
函數返回一個UIView
,我的UIView
將具有需要下載的圖像。 問題在於該函數本身期望返回UIView
類型,但是我無法知道setupCard
方法的完成塊setupCard
完成執行,因此我可能最終返回一個空FlatCard
而不是在完成塊中獲得的FlatCard
。 我嘗試將return a
添加到完成塊,但這是不允許的。 如何更改下面的代碼,以確保僅在完成補全塊執行后才歸還卡片。
func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
var a = FlatCard()
if let listings = all_listings {
if index < listings.count {
setupCard(index: index, listings: listings, { (complete, card) in
if (complete) {
a = card
}
})
return a
}
}
return a
}
func setupCard(index: Int, listings : [Listing], _ completionHandler: @escaping (_ complete: Bool, _ card : FlatCard) -> ()) -> (){
let curr_card = FlatCard()
if let main_photo_url = listings[index].pic1url {
URLSession.shared.dataTask(with: main_photo_url, completionHandler: { (data, response, error) in
if (error != nil) {
print(error)
return
}
DispatchQueue.main.async {
curr_card.mainFlatImage = UIImage(data: data!)
}
})
completionHandler(true,curr_card)
return
} else {
completionHandler(true,curr_card)
return
}
}
准備就緒之前,您無法退貨。
就個人而言,我將更新FlatCard,以便它可以下載圖像本身並在完成后更新其自己的視圖。
遵循以下原則
class FlatView: UIView {
var imageURL: URL? {
didSet {
if let imageURL = newValue {
// download image, if success set the image on the imageView
}
}
}
}
那么您在其他功能中需要做的就是...
func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
var a = FlatCard()
if let listings = all_listings {
if index < listings.count {
a.imageURL = listings[index].pic1url
}
}
return a
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.