How do I set the position of a UICollectionViewCell?

前端 未结 1 1690
执笔经年
执笔经年 2020-12-30 18:28

So as far as I know, the \"protocol method\":

(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *         


        
相关标签:
1条回答
  • 2020-12-30 18:48

    Can I assume you are also using an instance of UICollectionViewFlowLayout as your collection view's layout object?

    If so, the quick and dirty answer is to subclass UICollectionViewFlowLayout and override the -layoutAttributesForItemAtIndexPath: method:

    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 0 && indexPath.item == 2) // or whatever specific item you're trying to override
        {
            UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
            return layoutAttributes;
        }
        else
        {
            return [super layoutAttributesForItemAtIndexPath:indexPath];
        }
    }
    

    You will probably also need to override -layoutAttributesForElementsInRect::

    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        NSArray *layoutAttributes = [super layoutAttributesForElementInRect:rect];
        if (CGRectContainsRect(rect, CGRectMake(0, 0, 100, 100))) // replace this CGRectMake with the custom frame of your cell...
        {
            UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
            return [layoutAttributes arrayByAddingObject:layoutAttributes];
        }
        else
        {
            return layoutAttributes;
        }
    }
    

    Then use your new subclass in place of UICollectionViewFlowLayout when you create your collection view.

    0 讨论(0)
提交回复
热议问题