无法在 UICollectionViewCell 上设置阴影,并且具有圆角。一次只能制作一部作品



我有一个UICollectionViewCell子类,我需要绕角并添加阴影。 单元格看起来像一张方形卡片,单元格之间有大量的空间。

所以在每个单元格的"下面",我想添加一些阴影。我可以成功地做到这一点,但是我的单元格底部只有圆角。顶部只有正常的角落。我需要所有四个角的圆角。

我在这里找到了建议添加单独UIView作为subview UIViews的解决方案,但出于性能原因,我宁愿避免这种情况。

我确实找到了一个解决方案,那就是使用此方法,您将在下面的代码中找到该方法:

[UIBezierPath bezierPathWithRoundedRect: cornerRadius:]

但这对我也不起作用。是否有可能因为我试图只在单元格底部"下方"/添加阴影而对我不起作用?似乎这些答案中的大多数都是针对开发人员希望在整个单元格周围添加阴影的问题提供的。

我想我愿意为我的UICollectionViewCell子类添加一个特殊的subview,但我想将其用作最后的手段。

我的目标是iOS 7+并使用Xcode 6.1.1.

这是我在UICollectionViewCell子类中使用的代码,用于尝试实现阴影和圆角:

- (void)load:(CustomUserObject *)customObject
{
    self.customObject = customObject;
    // Round cell corners
    self.layer.cornerRadius = 12;
    // Add shadow
    self.layer.masksToBounds = NO;
    self.layer.shadowOpacity = 0.75f;
    self.layer.shadowRadius = 10.0f;
    self.layer.shouldRasterize = NO;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(self.frame.size.width/2 - (self.frame.size.width - 50)/2, self.frame.size.height, self.frame.size.width - 50, 10) cornerRadius:self.layer.cornerRadius].CGPath;
}

编辑:如果我将self.layer.masksToBounds设置为NO,阴影有效,但顶角不圆润。如果我将self.layer.masksToBounds设置为 YES ,阴影不起作用,但现在所有四个角都是圆形的。我只是不知道如何绕圆所有四个角并让阴影工作。

在看了蒂莫西·穆斯(Timothy Moose)在评论中分享的示例项目后,我意识到我实际上所做的一切都几乎和他一模一样。

出于沮丧,我重新审视了我细胞的nib文件,它终于击中了我。我在单元格的顶部添加了一条UIView。这个视图充当了彩色横幅,也充当了另一个UIImageViewUILabel的容器。

UICollectionViewCell的顶部成功地使顶角变圆,但您永远不会知道,因为彩色UIView位于单元格的顶部,并且与单元格一样宽。

愚蠢的错误,很多时候都是小事。

这是我用来实现四个圆角和UICollectionViewCell下方阴影的最终代码。 self.banner是隐藏单元格顶角的额外UIView

- (void)load:(CustomUserObject *)customObject
{
    self.customObject = customObject;
    // Round the banner's corners
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.banner.bounds
                                                   byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                         cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.banner.bounds;
    maskLayer.path = maskPath.CGPath;
    self.banner.layer.mask = maskLayer;
    // Round cell corners
    self.layer.cornerRadius = 10;
    // Add shadow
    self.layer.masksToBounds = NO;
    self.layer.shadowOpacity = 0.75f;
    self.layer.shadowRadius = 10.0f;
    self.layer.shouldRasterize = NO;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(self.frame.size.width/2 - (self.frame.size.width - 50)/2, self.frame.size.height, self.frame.size.width - 50, 10)].CGPath;
}
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
}

投影使用

cell.dropShadow()

最新更新