UICollectionViewCell with rounded corners AND drop shadow not working

jj0b picture jj0b · Aug 7, 2013 · Viewed 30.9k times · Source

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?

Answer

Gennadiy Ryabkin picture Gennadiy Ryabkin · Nov 17, 2014

Works for me great:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        ...
        cell.layer.masksToBounds = YES;
        cell.layer.cornerRadius = 6;
        ...
        return cell;
    }