我正在使用以下自定义布局从 Collection View 中的 url 加载图像 https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2并使用 kingfisher 将图像加载到 Collection View 单元格中,如下所示
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DbatCollectionViewCell",
for: indexPath) as! DbatCollectionViewCell
cell.layer.cornerRadius = 5
let debate = debatesArray[indexPath.row] as! NSDictionary
let debateDetails = debate.value(forKey: "debate") as! Debate
cell.dbatName?.text = debateDetails.title
if let debateImageUrl = URL(string: debateDetails.image!) {
cell.dbatImage.kf.setImage(with: debateImageUrl as Resource)
}
return cell
}
在该教程中,单元格的高度由图像高度提供,但我想根据图像的比例给出图像大小,无论是纵向还是横向图像。为此,我必须在
中找到图像的高度extension FavouriteCollectionViewController : DbatterLayoutDelegate {
// 1. Returns the photo height
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {
let heights = [125,150, 175,200,225,250]
let number = heights[Int(arc4random_uniform(UInt32(heights.count)))]
return CGFloat(number)
}
}
请指教如何做到这一点
最佳答案
为了实现这一点,我在上传图片时上传了包括高度和宽度在内的图片尺寸,并计算出图片高度如下
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat {
let debate = debatesArray[indexPath.row] as! NSDictionary
let debateDetails = debate.value(forKey: "debate") as! Debate
if debateDetails.image_size != nil {
let imageDictionary = debateDetails.image_size
let width = CGFloat((imageDictionary?.value(forKey: "width") as! NSString).floatValue)
let height = CGFloat((imageDictionary?.value(forKey: "height") as! NSString).floatValue)
let cellWidth = collectionView.contentSize.width / 2
let imageheight = cellWidth * height / width
return imageheight
}
return 200
}
关于swift - 根据图像高度获取 Collection View 自定义布局中单元格的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768677/