How to make UICollectionViewFlowLayout itemSize dynamic for screen size

前端 未结 2 2056
深忆病人
深忆病人 2021-02-19 11:02

I am working programmatically (no storyboard) and am having trouble making layout.itemSize dynamic for different screen sizes. I get this error message:

2条回答
  •  渐次进展
    2021-02-19 11:21

    Need to use the flow delegate method:

    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CGSize cellSize = CGSizeMake(width, height);
    
        return cellSize;
    }
    

    You specify the width and height float values to whatever you want.

    For example, lets say your CollectionView is vertical and you want a short header view, a big middle view and a small footer view, then you could do something like:

    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        CGSize cellSize;
    
        cellSize.width = self.view.bounds.size.width;
    
        if(indexPath.row == 0)
        {
            // header view height
            cellSize.height = 100;
        }
        else if(indexPath.row == 1)
        {
            // body view height
            cellSize.height = 500;
        }
        else
        {
            // assuming number of items is 3, then footer view is last view
            // footer view height
            cellSize.height = 100;
        }
    
        return cellSize;
    }
    

提交回复
热议问题