UICollectionViewCell 无法设置阴影

UICollectionViewCell can't set shadow

我想用 UICollectionViewCell 设置阴影,像这样:

我在自定义单元格中编写代码

override func awakeFromNib() {
        super.awakeFromNib()
        layer.shadowColor = UIColor(red: 0.7176470757, green: 0.7176470757, blue: 0.7176470757, alpha: 1.0000000000).CGColor
        layer.shadowOffset = CGSizeMake(0, 4)
        layer.shadowRadius = 2
       layer.shadowOpacity = 1
    }

但无法设置单元格阴影。设置阴影的所有子视图:

我该如何解决这个问题?

也添加这一行:

layer.masksToBounds = false

默认情况下它是 true 并将单元格限制在其框架大小内,通过将其设置为 false 允许单元格的阴影在其框架之外可见。

你应该把clipsToBounds.That是问题所在。

self.layer.shadowColor = UIColor(red: 0.7176470757, green: 0.7176470757, blue: 0.7176470757, alpha: 1.0000000000).CGColor
self.layer.shadowOffset = CGSizeMake(0, 4)
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 2.0
self.clipsToBounds = false
self.layer.masksToBounds = false

转到 collectionviewcell.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;
}

它会添加效果,如果你想添加一些 ui 然后在里面编码。