How to create a shadow for a UICollectionViewCell

I need to create a shadow for cells inside a UICollectionView . I subclassed the cells and inside the layoutSubviews I added the following code:

 -(void)layoutSubviews{ [super layoutSubviews]; self.layer.masksToBounds = NO; self.layer.shadowOpacity = 0.75f; self.layer.shadowRadius = 5.0f; self.layer.shadowOffset = CGSizeZero; self.layer.shadowColor = [UIColor blackColor].CGColor; self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath; } 

But the cells are getting taller, and this is the result:

enter image description here

If I remove:

 self.layer.masksToBounds = NO; 

Cells are displayed correctly (with a distance of 10 pixels between them), but the shadow is not visible. What am I doing wrong? Also, is it correct to add a shadow inside the layoutSubviews method?

+7
ios objective-c uicollectionview uicollectionviewcell
source share
3 answers

Found it, I forgot to add this line to layoutSubviews:

 self.clipsToBounds = YES; 

Cells now have both spacing and shadow

0
source share

You need to enable the shadow to create outside the borders;

 [cell.layer setMasksToBounds:NO]; 
+6
source share
  func dropShadow() { self.layer.masksToBounds = false self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor self.layer.shadowOpacity = 0.5 self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0) self.layer.shadowRadius = 4.0 self.layer.cornerRadius = 5.0 } //Direct Add Shadow to cell Cell.dropShadow() 
+3
source share

All Articles