peko
peko

Reputation: 11335

UICollectionViewCell position gets doubled

I just noticed that the center of uicollectionviewcells is half of the real center.

example:

setting frames for cells to:

[0] {{0, 0}, {100, 100}}
[1] {{100, 100}, {100, 100}}
[2] {{200, 200}, {100, 100}}
[3] {{300, 300}, {100, 100}}
[4] {{400, 400}, {100, 100}}
[5] {{500, 500}, {100, 100}}

note: this are the values i get from setFrame, and applyLayoutAttributes:

looks like this: actual look

but should look like this: how it should look

implementation of UICollectionViewLayout subclass

@implementation CVTLayout

- (void)prepareLayout {
    [super prepareLayout];

    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;


    CGSize size = CGSizeMake(100, 100);
    CGPoint center = CGPointMake(50, 50);
    NSMutableArray *cellAttributes = [[NSMutableArray alloc] init];
    for (int item = 0; item < [cvt.cellValues count]; item++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        attributes.size = size;
        attributes.center = center;
        [cellAttributes addObject:attributes];

        center.x += size.width;
        center.y += size.height;
    }
    cvt.cellAttributes = cellAttributes;
}

- (CGSize)collectionViewContentSize {
    return self.collectionView.bounds.size;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;
    return cvt.cellAttributes[indexPath.item];
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *layoutAttributes = [[NSMutableArray alloc] init];
    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;
    for (UICollectionViewLayoutAttributes *cellAttributes in cvt.cellAttributes) {
        if (CGRectIntersectsRect(rect, cellAttributes.frame)) {
            [layoutAttributes addObject:cellAttributes];
        }
    }
    return layoutAttributes;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return false;
}

@end

Upvotes: 2

Views: 279

Answers (1)

peko
peko

Reputation: 11335

Problem was setting the cell-label-frame to the cell-frame instead of the cell-bounds...

Upvotes: 1

Related Questions