下载图像后,我创建了一个返回图像垂直值的函数。
但是,图像的垂直值将失败,并返回CGFloat值。
此源代码用于下载并返回。
extension HomeViewController : PinterestLayoutDelegate
{
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat
{
let arts = self.artList
let model = arts![indexPath.row]
let urlString = model.url!
let urll = NSURL(string: urlString)
return downloadImage(from: urll! as URL)
}
}
extension HomeViewController
{
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ())
{
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL) -> CGFloat
{
getData(from: url)
{ data, response, error in
guard let data = data, error == nil else { return }
{
let image = UIImage(data: data)
let heightInPoints = image!.size.height
return heightInPoints
}
}
}
}
但是我遇到了一个错误
return heightInPoints
错误状态
void函数中意外的非void返回值
请帮助我。
答案 0 :(得分:0)
问题是您想在完成块内返回一个值,
func downloadImage(from url: URL,completion(_ value:CGFloat) -> Void )
{
getData(from: url)
{ data, response, error in
guard let data = data, error == nil else { return }
{
let image = UIImage(data: data)
let heightInPoints = image!.size.height
completion(heightInPoints)
}
}
}
顺便说一句,你不能这样做
return downloadImage(from: urll! as URL)
在heightForPhotoAtIndexPath
内,因为downloadImage是异步方法,它的响应取决于网络状态,而不是代码中的串行状态,它的调用看起来像
// array of heights
var arr = [CGFloat]()
let urll = URL(string: urlString)
downloadImage(from: urll!) { (value) in
print(value)
// append the value to it's corresponding index in an array of floats
DispatchQueue.main.async {
self.collectionview.reloadData()
}
}
如果可能的话,您需要为图像设置一个预定义的高度列表,否则请获取所有高度然后刷新收藏夹