Search code examples
iphoneioscocoa-touchcore-animationcalayer

Shadow not appearing for UIView using CALayer


I have a subclassed UIView loaded from a nib, and I cannot get a shadow to draw around it. I'm trying to get a shadow to appear around the entire view for quite some time now. I elected to place it in it's own sublayer to simplify animating it later. Here's the code:

-(void)awakeFromNib 
{
    self.clipsToBounds = NO;

    // set up the shadow layer
    CALayer *shadow = [CALayer layer];
    shadow.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height);
    shadow.shadowColor = [UIColor blueColor].CGColor;
    shadow.shadowRadius = 15.0;
    shadow.opacity = 1.0;
    [self.layer addSublayer:shadow];
    // I set this property so I have access to it later to more easily animate it.
    self.shadowLayer = shadow;
}

When I NSLog the shadowLayer property, the coordinates and frame are correct. It's matches the view it's backing.

I also set a border color and corner radius on self.layer and it appears correctly. If I put the shadow on self.layer it appears but it encompasses all the subviews of my parent UIView.

Any help is greatly appreciated.


Solution

  • Am assuming you have QuartzCore imported. I think you need to set & create a border to the UIView. The way to use this [self roundedLayerWithShadow:yourView.layer radius:5.0f];

    - (void)roundedLayerWithShadow:(CALayer *)viewLayer 
                            radius:(float)r 
    {
        [viewLayer setMasksToBounds:YES];
        [viewLayer setCornerRadius:r];        
        [viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
        [viewLayer setBorderWidth:1.0f];
    
        [viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
        [viewLayer setShadowOffset:CGSizeMake(0, 0)];
        [viewLayer setShadowOpacity:1];
        [viewLayer setShadowRadius:2.0];
        return;
    }