Поскольку изображение внутри модели необходимо повторно использовать в , следуя методам , поэтому загрузите его в самой модели с остальными данными из службы API.
func collectionView(collectionView: UICollectionView,
heightForImageAtIndexPath indexPath: IndexPath,
withWidth: CGFloat) -> CGFloat
&
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
Код для скачивания изображения в модели:
if let url = URL(string: "image_url_string") {
if let data = try? Data(contentsOf: url) {
image = UIImage(data: data)
}
}
В viewController
PinterestLayoutDelegate
:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as? HomeCollectionViewCell,
let arts = self.artList else { return HomeCollectionViewCell() }
if arts.count > indexPath.row {
let model = arts[indexPath.row]
cell.imgView.image = model.image //Which is downloaded in the model itself.
}
return cell
}
func collectionView(collectionView: UICollectionView, heightForImageAtIndexPath indexPath: IndexPath, withWidth: CGFloat) -> CGFloat {
// get image information
let image = self.artList[indexPath.item].image
return image.height(forWidth: withWidth) // cell Image Height
}
И не забудьте использовать это расширение:
public extension UIImage {
public func height(forWidth width: CGFloat) -> CGFloat {
let boundingRect = CGRect( x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRect(aspectRatio: size, insideRect: boundingRect)
return rect.size.height
}
}