iOS:自适应集合查看单元格宽度

时间:2014-12-23 14:58:27

标签: ios swift uicollectionview autolayout uicollectionviewcell

我正在尝试使用自适应列宽在iOS上制作网格视图。 在Android上,可以通过将stretchMode属性设置为spacingWidth来实现此目的。 此属性将单元格宽度作为最小宽度,如果有可用空间,则自动生长单元格,但不足以添加另一列,从而在列之间保持相同的空间。

我在iOS上没有找到任何办法。

Bad comportment screenshot

在iPhone 6上看起来像(左图),但在iPhone 5(右图)上,空间非常大而且丑陋。我不想自动调整细胞大小以避免这个大空间。

我怎么能在iOS上做到这一点?

(我正在使用Xcode 6.1)

由于

编辑: 这就是为什么我不想(黑色空间近似需要额外的单元格宽度,抱歉我的画很难看我很快就做了) enter image description here

编辑2:

我尝试使用此代码计算新大小,但结果是“奇怪”(错误的大小,位置),我想我错过了什么

    let CELL_SIZE : Float = 92
    let CELL_MARGIN : Float = 10
    let COLLECTION_VIEW_MARGIN : Float = 20 //Left right margin
    let screenWidth = Float(UIScreen.mainScreen().bounds.width)
    let numberOfCell =  Float(Int(screenWidth / (CELL_SIZE + CELL_MARGIN + COLLECTION_VIEW_MARGIN)))

    let oldCellSize = Float(cell.frame.width)
    var newCellSize : Float
    if(numberOfCell >= 2){
        newCellSize = (screenWidth / numberOfCell) - (CELL_MARGIN * (numberOfCell-1))
    } else {
        newCellSize = (screenWidth / numberOfCell)        }

    let indexPathRow = Float(indexPath.row)

    var xOffsetMultiplier = indexPathRow % numberOfCell
    if(xOffsetMultiplier == 0){
        xOffsetMultiplier = numberOfCell
    }

    var newX : Float = 0
    if(xOffsetMultiplier == 1){
        newX = COLLECTION_VIEW_MARGIN / 2
    } else {
        newX = (newCellSize + CELL_MARGIN) * (xOffsetMultiplier-1) + (COLLECTION_VIEW_MARGIN / 2)
    }

    var frame = CGRectMake(CGFloat(newX), cell.frame.minY, CGFloat(newCellSize), cell.frame.height)

    cell.frame = frame

此代码在我的ViewController

中的func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell中编写

1 个答案:

答案 0 :(得分:-1)

您应该根据集合视图大小使用UICollectionViewFlowLayout来采用单元格大小。