0

我正在实施 KolodaView,网址为:https ://github.com/Yalantis/Koloda 。该viewForCardAt函数返回一个UIView,我UIView将有一个需要下载的图像。问题是函数本身需要一个返回类型,UIView但我无法知道该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
    }
}
4

1 回答 1

1

你不能在它准备好之前退回东西。

就个人而言,我会更新 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
}
于 2017-12-21T13:47:01.950 回答