swift - 根据图像高度获取 Collection View 自定义布局中单元格的高度

标签 swift uicollectionview uicollectionviewcell

我正在使用以下自定义布局从 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/

相关文章:

ios - 我如何在 UITableViewCell 或 UICollectionViewCell 中编写仅影响其所在单元格的 UIButton 扩展?

uicollectionview - Swift 中自定义 UICollectionViewCell 上的标 checkout 口导致 Optional.None 崩溃

swift - do - try - catch 代码不尝试或捕获。只是做

arrays - 如何在 Swift 中连接或合并数组?

ios - UITableViewAutomaticDimension 不调整到 UILabel 文本高度

ios - 从设备获取所有图像并在 uicollectionview 中显示

ios - 如何在 Swift 中重置 UICollectionView

ios - 选择照片返回空白 UI

ios - 如何在 UIAlertViewController 中添加 UICollectionView?

ios - UICollectionView numberOfItemsInSection 被调用两次