简体   繁体   中英

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.

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

I struggled with the same, and it turns out you need to set shadowOpacity to 1.0. In your code you accidentally use opacity instead of shadowOpacity . That's the same issue I had.

In general, for the shadow to appear:

  • the shadowOpacity should be larger than 0
  • the shadowRadius should be larger than 0
  • the masksToBounds should be set to false (to avoid the clipping of the shadow)
  • the shadowColor should be different than the background color of the view's superview

Swift 4.2. example implementation:

let myCustomView = MyCustomView()
myCustomView.layer.shadowColor = UIColor.black.cgColor
myCustomView.layer.shadowOpacity = 0.15
myCustomView.layer.shadowRadius = 5
myCustomView.layer.masksToBounds = false
myCustomView.layer.shadowOffset = CGSize(width: 0, height: 2)

Aside from borderRadius , your shadow layer looks very much transparent. Therefore it will not drop any shadow on shadow.superlayer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM