【问题标题】:Get height of cell in collection view custom layout based on image height根据图像高度在集合视图自定义布局中获取单元格的高度
【发布时间】:2018-04-11 07:10:15
【问题描述】:

我正在使用以下自定义布局 https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2 从集合视图中的 url 加载图像,并使用 kingfisher 将图像加载到集合视图单元格中,如下所示

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

请告知如何操作

【问题讨论】:

  • 你解决了吗?
  • @Anushk 是的,我已经解决了。请参阅下面的答案

标签: swift uicollectionview uicollectionviewcell


【解决方案1】:

为了实现这一点,我在上传图片的过程中上传了图片大小,包括高度和宽度,并计算了图片高度如下

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 2016-11-10
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多