swift - UICollectionView 动态单元格高度(Pinterest 布局)

标签 swift uicollectionviewcell pinterest

我正在努力实现 Pinterest我的应用中的布局

我使用以下委托(delegate)方法来实现并动态设置单元格高度

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let boundingRect =  CGRect(x: 0, y: 0, width: self.view.frame.size.width / 2 - 20, height: CGFloat(MAXFLOAT))
    let data = articles[indexPath.row]
    let rect  = AVMakeRect(aspectRatio: (data.coverImage?.size)!, insideRect: boundingRect)
    return CGSize(width: rect.width, height: rect.height + 120) // Added 120 for a description I will add later 
}

但我得到了以下结果:

Here

灰色背景是单元格的背景,可以看到每个单元格都有自己的高度(符合预期) 但有多余的空格,我不知道如何删除。

我该如何解决这个问题?

最佳答案

你可以查看 raywenderlich 教程:

https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2

如果您想在到达最后一个单元格时加载新数据,则必须编辑一些代码。

在 PinterestLayout.swift 中,做以下更改:

 guard cache.isEmpty == true, let collectionView =   collectionView else {
        return
    }

 guard let collectionView = collectionView else {
        return
    } 

//这个文件名可能和你的不一样

在 PhotoStreamViewController.swift 中,添加如下代码:

   override func collectionView(_ collectionView:  UICollectionView, willDisplay cell: UICollectionViewCell,  forItemAt indexPath: IndexPath) {
      if (indexPath.row == photos.count - 1 ) {
     //it's your last cell

     // Add more data to the array according your requirement

     // After adding data reload collection view
        collectionView.reloadData()
        
    }
}

关于swift - UICollectionView 动态单元格高度(Pinterest 布局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693190/

相关文章:

swiftyjson - 调用可以抛出,但它被标记为 'try' 并且错误未被处理

ios - UICollectionView 仅在用户双击时调用 didSelectItemAtIndexPath,当用户单击时不会调用

Swift CollectionViewCells 问题

php - 处理 pinterest 中可变的图像尺寸,例如布局/加载

https - 使 Pinterest 个人资料小部件安全

swift - 仅在新添加的单元格处重新加载 TableView

swift - 为什么这在一个地方而不是另一个地方有效?

ios - Swift 停止卸载表格 View 单元格?

ios - UICOllectionview,滚动到标题中包含 NSString 的第一个单元格

html - 使用 Bootstrap 制作类似 Pinterest 的网格 : the boxes are not displayed right below each other