I want my UICollectionViewCells to have rounded corners and drop shadows but I have run into a problem where it seems I can only have one or the other, but not both.
To just round the corners I use this code in the initialization of the cell:
CALayer *layer = [self layer];
[layer setCornerRadius:4];
[layer setRasterizationScale:[[UIScreen mainScreen] scale]];
[layer setShouldRasterize:YES];
To just add a drop shadow I use this code in the initialization of the cell:
CALayer *layer = [self layer];
[layer setMasksToBounds:NO];
[layer setRasterizationScale:[[UIScreen mainScreen] scale]];
[layer setShouldRasterize:YES];
[layer setShadowColor:[[UIColor blackColor] CGColor]];
[layer setShadowOffset:CGSizeMake(0.0f,0.5f)];
[layer setShadowRadius:8.0f];
[layer setShadowOpacity:0.2f];
[layer setShadowPath:[[UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:layer.cornerRadius] CGPath]];
To try and have rounded corners and a drop shadow I use this code in the initialization of the cell:
CALayer *layer = [self layer];
[layer setMasksToBounds:NO];
[layer setCornerRadius:4];
[layer setRasterizationScale:[[UIScreen mainScreen] scale]];
[layer setShouldRasterize:YES];
[layer setShadowColor:[[UIColor blackColor] CGColor]];
[layer setShadowOffset:CGSizeMake(0.0f,0.5f)];
[layer setShadowRadius:8.0f];
[layer setShadowOpacity:0.2f];
[layer setShadowPath:[[UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:layer.cornerRadius] CGPath]];
but this results in the drop shadow only.
Is this a bug or am I doing something wrong?
If you place all your subviews into the
UICollectionViewCell
content view, which you probably are, you can set the shadow on the cell's layer and the border on thecontentView
's layer to achieve both results.Swift 4.0
There is tricky moment. Cutting corners and dropping shadow is mutually exclusive function in one layer. Dropping shadow is frame extension process, but corners is the process of masking to bounds.
Solution is in function separation. I recommend setup shadow for the cell layer, but cut corners for contentView layer of that cell.
I think I ran into a similar issue. My problem was that clipping in my subviews of the
UICollectionViewCell
didn't work properly with shadows and rounded borders. The exact same code worked just fine before when I had that view (as a standardUIView
subclass though) in aUIScrollView
.So long story short, I moved all this setup from the
initWithCoder
to a later place after getting it from-dequeueReusableCellWithReuseIdentifier:forIndexPath:
. Solved the problem for me. Seems likeUICollectionViews
are doing something I wouldn't expect to their cells' layers at some point?If you are using a subclass to make the collection just make sure you do the following.
works like a charm.
Works for me great: