Reputation: 691
I am trying to implement a simple grid of small rectangular cells separated by a grey line. Also, the four corners of my collection view should have rounded corners.
I found that I can't just set the cornerRadius
on the UICollectionView
layer as that puts the whole collectionview
in a 'box' and it looks weird whilst scrolling etc. It looks like I have to round the corner of the 4 cells at each corners.
I ran into the challenges of
I would be grateful for some pointers. I managed to do it but using graphics for the top, bottom, left and right borders as well as to simulate the rounded edges. And this works for me as my grid has fixed values so I could calculate and work out for each cell what their position was in the grid.
Thanks!
Upvotes: 1
Views: 2050
Reputation: 255
You can set the border of the cells by doing something like
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [...]
if (indexPath.row == 0 && indexPath.section == 0) { // top left
[self roundView:cell.view onCorner:UIRectCornerTopLeft radius:yourRadius];
} else [...]
}
I suggest you to use a function similar to the next one for rounding the corner of the cells
- (void)roundView:(UIView *)view onCorner:(UIRectCorner)rectCorner radius:(float)radius {
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(radius, radius)];
CAShapeLayer *maskLayer = [CAShapeLayer new];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
[view.layer setMask:maskLayer];
}
To set the border between the cells you should create a custom UICollectionViewFlowLayout
and set up the frames of all your cells with the method
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
Upvotes: 2