UICollectionViewFlowLayout doesn't use integra

2019-03-17 00:35发布

问题:

I have recently started using UICollectionView, and am a bit confused about the UICollectionViewFlowLayout. It would seem that the frames for each cell in the collection view are calculated with equal space between each item. This causes the frames of some of the cells to have fractional positions, which will cause blurry labels and misaligned image pixels and so on.

I am surprised to find that there are no questions about this on stack overflow though, which makes me think I am doing something wrong. I have created a test project that demonstrates the problem quite simply:

https://github.com/rmaz/BlurryCollectionView

Is this really the standard behaviour? It seems to me that this makes the flow layout basically unusable without subclassing. Or am I missing something?

回答1:

Workaround: subclass UICollectionViewFlowLayout, override UICollectionViewLayout's -layoutAttributesForElementsInRect: and for every layout attributes make the frame integral:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *allLayoutAttributes = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes *layoutAttributes in allLayoutAttributes) {
        layoutAttributes.frame = CGRectIntegral(layoutAttributes.frame);
    }
    return allLayoutAttributes;
}

Note: iOS 7 UICollectionViewFlowLayout has been fixed to always use integral frames for its cells' frames. I recommend keeping the fix for iOS 6.x but conditionally deprecate it for iOS 7 and newer.

Best, Raphael