how to make dynamic width of the UICollectionViewCell

前端 未结 5 1333
粉色の甜心
粉色の甜心 2021-01-03 05:59

I want to set the width of UICollectionViewCell dynamically. I found some code in swift and I want the code in Objective-C.

let flowLayout = col         


        
5条回答
  •  礼貌的吻别
    2021-01-03 06:24

    Swift 2.2

    override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        var flowLayout = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout)
        if indexPath.item % 3 == 0 {
            var cellWidth: Float = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right))
            return CGSizeMake(cellWidth, cellWidth / 2)
        }
        else {
            var cellWidth: Float = (CGRectGetWidth(collectionView.frame) - (flowLayout.sectionInset.left + flowLayout.sectionInset.right) - flowLayout.minimumInteritemSpacing) / 2
            return CGSizeMake(cellWidth, cellWidth)
        }
    }
    

    Swift 3.0

    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var flowLayout: UICollectionViewFlowLayout? = (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)
        if indexPath.item % 3 == 0 {
            var cellWidth: Float? = (collectionView.frame.width - (flowLayout?.sectionInset?.left + flowLayout?.sectionInset?.right))
            return CGSize(width: CGFloat(cellWidth), height: CGFloat(cellWidth / 2))
        }
        else {
            var cellWidth: Float? = (collectionView.frame.width - (flowLayout?.sectionInset?.left + flowLayout?.sectionInset?.right) - flowLayout?.minimumInteritemSpacing) / 2
            return CGSize(width: CGFloat(cellWidth), height: CGFloat(cellWidth))
        }
    }
    

提交回复
热议问题