【发布时间】:2017-08-16 14:44:41
【问题描述】:
我采用了一个 iOS 项目,需要为对象添加图像方法。我在想这样的事情。但是,我将如何声明 image 方法以返回 UIImage?或者这甚至可能吗?
从更大的角度来看,这些项目将位于 UICollection 视图中,因此我需要加载图像以确定自定义 UICollectionViewCell 的高度。
class Item {
var imageURL = "https://s3-us-west-1.amazonaws.com/bucket/images/26882/abc.jpg?1477323919"
// probably need to change this
func image() -> UIImage {
URLSession.shared.dataTask(with: NSURL(string: imageURL)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
return image
})
}).resume()
}}
}
编辑#1
这是此调用的使用者 - 不确定我是否可以调整它以使其适合异步调用以获取图像。在 JSON 调用中向下发送元数据可能比通过此异步调用计算它更容易。
extension MasterViewController: MosaicLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, heightForImageAtIndexPath indexPath: IndexPath, withWidth width: CGFloat) -> CGFloat {
let item = items[indexPath.item]
let image = item.image() // need to get this height
let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRect(aspectRatio: image.size, insideRect: boundingRect)
return rect.height
}
【问题讨论】:
标签: ios asynchronous