如何为UICollectionViewCell创建阴影

时间:2016-05-04 09:09:55

标签: ios objective-c uicollectionview uicollectionviewcell

我需要为UICollectionView内的单元格创建一个阴影。我已将这些单元格子类化,并在layoutSubviews内部添加了以下代码:

-(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;


}

但是细胞越来越高,这就是结果:

enter image description here

如果我删除了:

self.layer.masksToBounds = NO;

正确显示细胞(它们之间的距离为10px),但阴影不可见。我究竟做错了什么?另外,在layoutSubviews方法中添加阴影是否正确?

3 个答案:

答案 0 :(得分:7)

您需要启用在边界之外创建阴影;

[cell.layer setMasksToBounds:NO];

答案 1 :(得分:3)

    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()

答案 2 :(得分:0)

找到它,我忘了在layoutSubviews中添加这一行:

self.clipsToBounds = YES;

现在细胞有间距和阴影