Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create shadow for UICollectionViewCell

I need to create a shadow for the cells inside a UICollectionView. I've subclassed the cells and inside the layoutSubviews I've 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 gets higher and this is the result:

enter image description here

If I remove the:

self.layer.masksToBounds = NO;

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

like image 221
LS_ Avatar asked May 04 '16 09:05

LS_


2 Answers

You need to enable the shadow to be created outside of the bounds;

[cell.layer setMasksToBounds:NO];
like image 181
Pushp Avatar answered Sep 22 '22 20:09

Pushp


    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()
like image 22
sandip jadhav Avatar answered Sep 23 '22 20:09

sandip jadhav