ios - 根据框架大小自动调整 UICollectionViewCell 中的单元格大小

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我怎样才能使 Collection View 中的单元格自动调整大小,以便至少四个单元格可以放在一行中,如果框架大小是 iPad 的,那么更多的单元格可以放在一行中。四个单元格应该是一行中的最小单元格数,请参阅下面的图片以进一步说明:

我有一个 Collection View ,它允许我使用选择器 View Controller 添加图像,起初 Collection View 如下所示:

enter image description here

我可以进一步向这个 Collection View 添加图像,在添加多张图像后,它会:

enter image description here

现在如果有四张图片,第四张转到下一行,我希望系统根据帧大小自动调整单元格大小,以便一行中至少显示四个单元格。我是新手,对收藏 View 还很陌生,有人可以帮我解决这个问题吗?

最佳答案

您可以使用以下方法决定 collectionview 单元格的大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{

    // Return different cells size
    let screenBounds = UIScreen.main.bounds
    var width = screenBounds.width
    let totalLeftRightInsect = 16      
    let minimumsSpaceBetweenCell = 5

    switch (Condition for detecting device ) {
    case "iPhone":
        let numberOfCell = 4 
        let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
        width = (width - totalSpace) / CGFloat(numberOfCell)
        return CGSize(width: width, height: width)

    case "ipad":
         let numberOfCell = 6
         let totalSpace = CGFloat(( numberOfCell * spaceBetweenCell) + totalLeftRightInsect)
        width = (width - totalSpace) / CGFloat(numberOfCell)
        return CGSize(width: width, height: width)

    default:
        return CGSize(width: 0.0, height: 0.0)
    }}

关于ios - 根据框架大小自动调整 UICollectionViewCell 中的单元格大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230257/

相关文章:

ios - 可折叠表格 View 错误

ios - 将父 ViewController 值发送到 UICollectionViewCell 单元格

ios - LLDB 中的简单宏?

ios - 快速创建板载屏幕

ios - 如何根据百分比制作圆圈?

ios - 如何在 Xcode (swift) 中隐藏标签栏?

ios - 在动态框架 Objective C 和 Swift 中混合搭配实现目标协议(protocol)的 Swift 类,但找不到定义

ios - UICollectionViewCell 自定义 Segue ViewController 连接错误

ios - 在 UICollectionView swift 中折叠一个部分的单元格

ios - UIImageView 获取显示图像的位置