Reputation: 6940
I have collection view with custom flow layout and i wonder why i have extra space like that (right side):
It may hard to notice here, though, but you may see gray gap between right side and cell.
Here is how i override standard collection view flow layout to remove horizontals gaps:
@implementation CalendarFlowLayout
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *answer = [super layoutAttributesForElementsInRect:rect];
NSLog(@"layout blck passed");
for(int i = 1; i < [answer count]; ++i) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
NSInteger maximumSpacing = 0;
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return answer;
}
@end
Cell size calculated as follow:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(SCREEN_WIDTH/7, (SCREEN_HEIGHT-NAVBAR_HEIGHT-STATUS_BAR_HEIGHT)/6);
}
Those macros above look like that:
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
It has been tested and it return correct output.
Also, if i set width to SCREEN_WIDTH/3, there is will be no gap.
How to remove it? Why is that happen?
Upvotes: 0
Views: 92
Reputation: 2435
The problem is that the width of the cell (eg. SCREEN_WIDTH/3
) is not a divisor of SCREEN_WIDTH
. Correct divisors of SCREEN_WIDTH
(375, as you said in comments) are 3, 5, 25 and 125 (125*3=375).
But As there are different screen size among all iOS devices, I think you should manage the problem differently. For example, you should choose a specific cell width and try to center the collection view in its container, so the extra-space will always be divided on both left and right side of the collection view.
Upvotes: 1
Reputation: 5935
375 / 3 = 125
375 / 7 = 53.57142857142857
You can't really light a half a pixel, so it is probably rounding down, leaving you with a gap. Make sure your size is a multiple of your subview size (or add a pixel to the rightmost object if it's not).
Upvotes: 2