gpt4 book ai didi

ios - 关于在 Swift 4 中返回 CGFloat 值

转载 作者:行者123 更新时间:2023-11-28 07:37:36 25 4
gpt4 key购买 nike

下载图像后,我创建了一个返回图像垂直值的函数。

但是,图像的垂直值将失败并返回 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

错误状态

Unexpected non-void return value in void function

请帮帮我。

最佳答案

问题是你想在完成 block 中返回一个值,你需要

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()
}
}

如果可能,您需要为图像预定义高度列表,如果没有,则获取所有高度然后刷新集合

关于ios - 关于在 Swift 4 中返回 CGFloat 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com