Shadow not showing when background color is clear color

If you specify shadowPath property

shadowView.layer.shadowPath =
  UIBezierPath(
   roundedRect: shadowView.bounds,
   cornerRadius: 10).cgPath

(Or whatever corner radius is desired.)

it will work even with .clear backgroundColor.

Note that you of course have to do this in layoutSubviews of the view in question.

Here's an actual full working example:

import UIKit

@IBDesignable class LonelyShadow: UIView {

    let corner: CGFloat = 20

    override init(frame: CGRect) {
        super.init(frame: frame)
        common()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    private func common() {

        backgroundColor = .clear
        clipsToBounds = false

        layer.shadowColor = UIColor.yourColor.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 25)
        layer.shadowOpacity = 0.3
        layer.shadowRadius = 40
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.shadowPath = UIBezierPath(
          roundedRect: bounds, cornerRadius: corner).cgPath
    }
}

Equivalent to @Rok Jark's answer in Swift 4:

self.layer.shadowColor = UIColor(white: 0.5, alpha: 1).cgColor
self.layer.shadowRadius = 4.0
self.layer.shadowPath = CGPath.init(rect: CGRect.init(x: 0, y: 0, width: 50, height: 50), transform: nil)
self.layer.shadowOpacity = 1.0;
self.layer.shadowOffset = CGSize(width: 1, height: 1)

The problem is, that shadow actually takes into account the 'upper' layer. If there's nothing on it there will be no shadow: How Shadows Work

EDIT:

There is this recipe copied from paste bin

view.layer.shadowColor = [UIColor colorWithWhite:.5 alpha:1].CGColor;
view.layer.shadowRadius = 4.0f;
view.layer.shadowPath = CGPathCreateWithRect(CGRectMake(0, 0, 50, 50), NULL);
view.layer.shadowOpacity = 1.0f;
view.layer.shadowOffset = CGSizeMake(1, 1);

But I doubt this will be of any use to you: the result is a view 'painted' with color of a shadow and a shadow around it.

Tags:

Ios

Calayer