How do I set the position of a UICollectionViewCel

2019-02-05 10:11发布

问题:

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

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

Automatically sets the bounds of the cell I created. This is all fine and dandy for my of the UICollectionViewCells, but I need one of them to be in a location that I specify. Any pointers in the right direction would be appreciated.

回答1:

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.