仅更改uicollectionviewcell的宽度

时间:2014-10-15 18:09:44

标签: ios swift collectionview

我正在尝试使用根据屏幕大小更改宽度的单元格进行集合视图。在iOS和swift中。目前我正在使用函数“sizeForItemAtIndexPath”。我不能只输入高度,因为我在故事板中有不同类型的单元格,具有不同的高度。所以我希望高度相同,但能够改变宽度

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(changingWidth, sameHeight)
}

2 个答案:

答案 0 :(得分:1)

快速

我尝试过,对我有用:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    var height:CGFloat = 10.0  // Fallback value
    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        height = layout.itemSize.height
    }
    return CGSize(width: collectionView.frame.width, height: height)
}

答案 1 :(得分:0)

这将是我的第一次尝试,但我不知道调用的顺序 - 这可能会设置无限递归或以其他方式破坏你的东西:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
        return CGSizeMake(changingWidth, cell.frame.height)
    } else {
        return CGSizeMake(changingWidth, defaultHeight)
    }
}