Swift 根据图像高度获取集合视图自定义布局中单元格的高度
我从集合视图中的url加载一个图像,使用以下自定义布局,并使用翠鸟将图像加载到集合视图单元格中,如下所示Swift 根据图像高度获取集合视图自定义布局中单元格的高度,swift,uicollectionview,uicollectionviewcell,Swift,Uicollectionview,Uicollectionviewcell,我从集合视图中的url加载一个图像,使用以下自定义布局,并使用翠鸟将图像加载到集合视图单元格中,如下所示 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withR
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
}
你能解决它吗?@Anushk是的,我已经解决了。见下面我的答案