Can't set shadow on UICollectionViewCell and have rounded corners. Can only make one work at a time

吃可爱长大的小学妹 提交于 2019-12-05 21:32:57

After looking at the sample project that Timothy Moose was kind enough to share in the comments, I realized that I was literally doing everything almost exactly like he was.

Out of frustration, I revisited my cell's nib file and it finally hit me. I had added a UIView to the top of the cell. This view was serving as a colored banner and was also functioning as a container for another UIImageView and a UILabel.

The top of the UICollectionViewCell was successfully rounding the top corners, but you never would have known because the colored UIView was at the top of the cell and was just as wide as the cell.

Stupid mistake, many times its the little things.

Here is the final code I am using to achieve four rounded corners and a shadow underneath the UICollectionViewCell. self.banner is the extra UIView that was hiding the cell's top corners:

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

//To drop shadow use

cell.dropShadow()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!