UICollectionView Cell Shadow

时间:2017-01-05 14:58:30

标签: ios objective-c uicollectionview uicollectionviewcell calayer

我正在尝试向自定义UICollectionViewCell添加阴影,这是我在自定义集合视图单元类中使用的代码:

self.layer.shadowOffset = CGSizeMake(1, 0);
self.layer.shadowColor = [[UIColor blackColor] CGColor];
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = .25;

这为集合视图单元的组件提供了阴影。

4 个答案:

答案 0 :(得分:14)

不要忘记添加这两行

self.clipsToBounds = false      
self.layer.masksToBounds = false

答案 1 :(得分:4)

cell.layer.backgroundColor不应该是清晰的颜色

cell.layer.backgroundColor = UIColor.white.cgColor

答案 2 :(得分:4)

Swift 4.2和xcode 10

这里是添加阴影的代码。

    cell.contentView.layer.cornerRadius = 2.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = true

    cell.layer.backgroundColor = UIColor.white.cgColor
    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 2.0)//CGSizeMake(0, 2.0);
    cell.layer.shadowRadius = 2.0
    cell.layer.shadowOpacity = 1.0
    cell.layer.masksToBounds = false
    cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds, cornerRadius:cell.contentView.layer.cornerRadius).cgPath

答案 3 :(得分:0)

转到CustomCollectionViewCell.m文件 为我工作。希望它有所帮助...

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //////// make shadow  of total view
        self.clipsToBounds = NO;
        self.layer.masksToBounds = NO;
        self.layer.shadowRadius = 5;
        self.layer.shadowOpacity = 0.5;
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(0, 1);
        self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;

        // make radius of the cell
        self.layer.cornerRadius = 5;

    }
    return self;
}