UICollectionView with dynamic height not getting same space between cell

后端 未结 6 1788
野的像风
野的像风 2021-02-14 02:59

I am having similar problem like this

I am generating height of view at run time.Here is my code

@interface CollectionViewController ()
{
    NSMutableAr         


        
6条回答
  •  粉色の甜心
    2021-02-14 03:42

    The class that you inherited from UICollectionViewFlowLayout must contain methods :

    - (CGSize)collectionViewContentSize
    {
        return CGSizeMake(200, 200) // as per your cell size
    }
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
        for (UICollectionViewLayoutAttributes* attributes in attributesToReturn)
        {
            if (nil == attributes.representedElementKind)
            {
                NSIndexPath* indexPath = attributes.indexPath;
                attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
            }
        }
        return attributesToReturn;
    }
    
    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewLayoutAttributes* currentItemAttributes =
        [super layoutAttributesForItemAtIndexPath:indexPath];
    
        if (!currentItemAttributes)
        {
            currentItemAttributes = [UICollectionViewLayoutAttributes
                                     layoutAttributesForCellWithIndexPath:indexPath];
        }
        return currentItemAttributes;
    }
    

    And in Your CollectionViewController add

    #pragma mark - Collection View Datasource
    
    - (CGSize)collectionView:(UICollectionView *)collectionView
                      layout:(UICollectionViewLayout  *)collectionViewLayout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        // Adjust cell size for orientation
        if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
        {
            return CGSizeMake(150, 230);
        }
        return CGSizeMake(150, 230);
    }
    

提交回复
热议问题