根据帧大小自动调整UICollectionViewCell中的单元格

时间:2016-02-05 17:39:19

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

如何使集合视图中的单元格自动调整大小,以便最少四个单元格至少可以放在一行中,如果框架大小是iPad的大小,则更多单元格可以放入行中。四个单元格应该是一行中最小的单元格数量,请参阅下面的图片以进一步说明:

我有一个集合视图,允许我使用选择器视图控制器添加图像,首先集合视图如下所示:

enter image description here

我可以进一步将图像添加到此集合视图中,并在添加多个图像后,它希望:

enter image description here

现在如果有四个图像,第四个图像进入下一行,我希望系统根据帧大小自动调整单元格,以便在一行中显示最少四个单元格。我是一个新手,对收集视图很新,有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法决定collectionview&cell的大小:

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

答案 1 :(得分:0)

回答Swift3,Xcode 8,水平间距固定:

所有早期答案的问题是给定单元格大小CGSizeMake(cellWidth,cellWidth)实际上占用了所有屏幕,没有空间用于边缘线,因为collectionView试图通过减少每个元素中的一个元素来调整行/列间距行和不需要的额外间距。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let linespacing = 5          //spacing you want horizantally and vertically
        let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
        let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
        return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing)

}

相关问题