UICollectionView中的动态单元格高度

时间:2017-11-21 15:11:25

标签: ios swift uicollectionview uicollectionviewcell

我的自定义UICollectionViewCell包含许多对象,但总体而言,它需要连接到数据库,抓取存储的图片网址并通过附加每张照片填充UIImageView(数字)照片是可选的 - 从1到10)到UIStackView

现在,除了单元格的高度是硬编码之外,我得到了所有内容,因此,它无法正常工作。我不知道如何获得这个尺寸。这是我的代码。

这是高度硬编码的地方。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,   sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let width = collectionView.bounds.width
    let size = CGSize(width: width, height: 800)
    return size
}

这是设置UIImageView的地方。 photoURLs是数据库中下载的URL数组。

if let photoURLString = post?.photoURLs
{
    for urlString in photoURLString
    {
       let photoURL = URL(string: urlString)
       let imageView = UIImageView()
       imageView.sd_setImage(with: photoURL)
       imageView.contentMode = .scaleAspectFill
       imageView.clipsToBounds = true
       imageView.widthAnchor.constraint(equalTo: postImagesStackView.widthAnchor)
       postImagesStackView.addArrangedSubview(imageView)
       postImagesStackView.layoutIfNeeded()
     }
}

另外,如何在每张照片之间留一点空间?喜欢1分?

2 个答案:

答案 0 :(得分:0)

我认为你需要计算细胞高度。 在这种情况下,在调用reload collectionView之前对图像高度求和,或者修复imageView高度并将图像计数与高度相乘。

另一个解决方案是为每个图像制作单元格。 您可以使用section和custom collectionview布局而不是stackview。

答案 1 :(得分:0)

如同woosiki所示,您可以尝试根据返回的图像尺寸计算一个值。一旦获得响应并计算完整高度,则调用collectionView.reloadData()并为每个后备对象引用该fullHeight属性。像下面这样的东西,如果让let / where和default / max height,它会更安全。

func collectionView(_ collectionView: UICollectionView, layout 
collectionViewLayout: UICollectionViewLayout,   sizeForItemAt 
indexPath: IndexPath) -> CGSize
{
    let imageObject = dataSource.items[indexPath.row]
    let width = collectionView.bounds.width
    let size = CGSize(width: width, height: imageObject.fullHeight)
    return size
}

对于边框/间距,如果您最终还是包含字幕或元数据,或者只是尝试文档示例,则可能包含略大的父视图:

https://developer.apple.com/documentation/uikit/nslayoutanchor

相关问题