24

I looked up but I couldn't find how I can add an inner shadow to UIView, only top (from top to bottom) for Swift. What is the best way add inner circle in Swift?

Edit: I've found some questions & answers on SO however they are either in obj-c or looks so complicated. I was just looking for a more Swifty way, if there is any

What I want to achieve:

enter image description here

5
  • 3
    github.com/inamiy/YIInnerShadowView
    – Arbitur
    Jun 7, 2016 at 1:08
  • @Arbitur, your link is in objective-c which I couldn't translate. In its SO answer, it looks quite complicated chunk of code and its all sides.. It's not also using something easy like CGSizeMake, that's why I wanted to ask about it. I was just looking for a more Swifty way
    – senty
    Jun 7, 2016 at 1:13
  • 1
    If you want to make sure the shadow stays along the upper border only, no matter the blur radius/offset/etc. and doesn't bleed into the other borders, your best bet is to add a UIImageView as a child view, stuck to the top border and stretching along the full width. If you need a special treatment at the side edges (like your screenshot seems to suggest) perhaps a stretchable image with insets will do the trick. Jun 7, 2016 at 1:51
  • Although it would be smarter perhaps to override drawRect(_:) and do everything with Core Graphics. No extraneous extra views, no image assets needed, but more advanced code. Jun 7, 2016 at 1:51
  • @NicolasMiari I think that would be a good workaround, but not then answer. Thanks; and I'd love to learn the answer :)
    – senty
    Jun 7, 2016 at 2:09

7 Answers 7

29

Here's a pure Swift version that I whipped up:

public class EdgeShadowLayer: CAGradientLayer {

    public enum Edge {
        case Top
        case Left
        case Bottom
        case Right
    }

    public init(forView view: UIView,
                edge: Edge = Edge.Top,
                shadowRadius radius: CGFloat = 20.0,
                toColor: UIColor = UIColor.white,
                fromColor: UIColor = UIColor.black) {
        super.init()
        self.colors = [fromColor.cgColor, toColor.cgColor]
        self.shadowRadius = radius

        let viewFrame = view.frame

        switch edge {
            case .Top:
                startPoint = CGPoint(x: 0.5, y: 0.0)
                endPoint = CGPoint(x: 0.5, y: 1.0)
                self.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: shadowRadius)
            case .Bottom:
                startPoint = CGPoint(x: 0.5, y: 1.0)
                endPoint = CGPoint(x: 0.5, y: 0.0)
                self.frame = CGRect(x: 0.0, y: viewFrame.height - shadowRadius, width: viewFrame.width, height: shadowRadius)
            case .Left:
                startPoint = CGPoint(x: 0.0, y: 0.5)
                endPoint = CGPoint(x: 1.0, y: 0.5)
                self.frame = CGRect(x: 0.0, y: 0.0, width: shadowRadius, height: viewFrame.height)
            case .Right:
                startPoint = CGPoint(x: 1.0, y: 0.5)
                endPoint = CGPoint(x: 0.0, y: 0.5)
                self.frame = CGRect(x: viewFrame.width - shadowRadius, y: 0.0, width: shadowRadius, height: viewFrame.height)
        }
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }   
}

To use it,

let topShadow = EdgeShadowLayer(forView: targetView, edge: .Top)
targetView.layer.addSublayer(topShadow)

Note that it defaults to a black-to-white gradient that's 20 points deep.

The full code, with a sample UIViewController that lets you toggle shadows on all four corners of a view, can be found at https://github.com/jrtibbetts/Tenebrae. I've also documented the EdgeShadowLayer pretty thoroughly.

5
  • What is targetView and what is view here? Aren't both same? Mar 15, 2018 at 20:38
  • 1
    Updated the answer. Mar 16, 2018 at 14:21
  • Could you use UIColor.clear as the toColor so the second color would be transparent? That way it could be independent of the underlying view's color. Apr 3, 2019 at 21:27
  • Sure; I don’t see why not.
    – NRitH
    Apr 3, 2019 at 21:29
  • I implemented it. See my post below for code and screenshots. Apr 4, 2019 at 4:40
16

I used implement inner shadow to UIView using Objective-C. I try to translate code into swift. Please forgive me for my poor swift syntax

you can call function below in UIView.didMoveToSuperview

func drawShadow() {
    if nil == self.shadowLayer {
        let size = self.frame.size
        self.clipsToBounds = true
        let layer: CALayer = CALayer()
        layer.backgroundColor = UIColor.lightGrayColor().CGColor
        layer.position = CGPointMake(size.width / 2, -size.height / 2 + 0.5)
        layer.bounds = CGRectMake(0, 0, size.width, size.height)
        layer.shadowColor = UIColor.darkGrayColor().CGColor
        layer.shadowOffset = CGSizeMake(0.5, 0.5)
        layer.shadowOpacity = 0.8
        layer.shadowRadius = 5.0
        self.shadowLayer = layer

        self.layer.addSublayer(layer)
    }
}
5
  • 1
    By far the best answer. IMHO. Other answers use gradients, which are not how shadows are drawn in Core Graphics.
    – beyowulf
    Jun 7, 2016 at 11:33
  • 6
    Where does self.shadowLayer come from?
    – Jon Vogel
    Dec 19, 2017 at 1:10
  • 1
    @JonVogel Probably just a CALayer property to keep track of whether the shadow is added yet or not and to access and edit it later on in the view's lifecycle. Removing the check and the assignment to it is fine if all you want to do is add a shadow once.
    – kevin
    May 23, 2018 at 6:29
  • self.shadowLayer seems to be missing piece. Can you explain where it is coming from? Nov 23, 2018 at 0:50
  • 1
    @Jayprakash Dubey Just a property, such as private var shadowLayer: CALayer?
    – J.Hunter
    Nov 23, 2018 at 5:46
8

I tweaked the modification made by @anoop4real using clear as the toColor and made the interface more in-line with the shadow settings in CALayer, including defaults, with the exception of opacity, which is set to 0.0 by default. I went with a default of 0.6 since it looked the most natural.

extension UIView {
    func addShadow(to edges: [UIRectEdge], radius: CGFloat = 3.0, opacity: Float = 0.6, color: CGColor = UIColor.black.cgColor) {

        let fromColor = color
        let toColor = UIColor.clear.cgColor
        let viewFrame = self.frame
        for edge in edges {
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [fromColor, toColor]
            gradientLayer.opacity = opacity

            switch edge {
            case .top:
                gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
                gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
                gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: radius)
            case .bottom:
                gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
                gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
                gradientLayer.frame = CGRect(x: 0.0, y: viewFrame.height - radius, width: viewFrame.width, height: radius)
            case .left:
                gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
                gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
                gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: radius, height: viewFrame.height)
            case .right:
                gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
                gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
                gradientLayer.frame = CGRect(x: viewFrame.width - radius, y: 0.0, width: radius, height: viewFrame.height)
            default:
                break
            }
            self.layer.addSublayer(gradientLayer)
        }
    }

    func removeAllShadows() {
        if let sublayers = self.layer.sublayers, !sublayers.isEmpty {
            for sublayer in sublayers {
                sublayer.removeFromSuperlayer()
            }
        }
    }
}

The top view is the default settings, and the bottom uses a radius of 5.0 to show more clearly.

view1.addShadow([.top, .bottom, .left, .right])
view2.addShadow([.top, .bottom, .left, .right], radius: 5.0)
view2.backgroundColor = .orange

views with inner shadow

3
  • 1
    Your removeAllShadows removes all sublayers of UIView at all! For proper category usage, you should add associated object in addShadow and remove them in removeShadows, or just delete this remove method from your implementation
    – iago849
    Aug 14, 2019 at 8:47
  • This produces a multiplicative effect where the shadows overlap each other. i.e. the corners become darker.
    – Womble
    Oct 6, 2020 at 23:39
  • Bottom and Right show only display when tap cell in UIcollectionviewcell
    – AmitTank
    Jan 23, 2021 at 23:28
6

I updated @NRitH's answer and made an extension out of it also modified so that you can manipulate multiple edges in one go

usage

myview.addShadow(to: [.top,.bottom], radius: 15.0)

extension UIView{

    func addShadow(to edges:[UIRectEdge], radius:CGFloat){

        let toColor = UIColor(colorLiteralRed: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1.0)
        let fromColor = UIColor(colorLiteralRed: 188.0/255.0, green: 188.0/255.0, blue: 188.0/255.0, alpha: 1.0)
        // Set up its frame.
        let viewFrame = self.frame
        for edge in edges{
            let gradientlayer          = CAGradientLayer()
            gradientlayer.colors       = [fromColor.cgColor,toColor.cgColor]
            gradientlayer.shadowRadius = radius

            switch edge {
            case UIRectEdge.top:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.bottom:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.frame = CGRect(x: 0.0, y: viewFrame.height - gradientlayer.shadowRadius, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.left:
                gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            case UIRectEdge.right:
                gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.frame = CGRect(x: viewFrame.width - gradientlayer.shadowRadius, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            default:
                break
            }
            self.layer.addSublayer(gradientlayer)
        }

    }

    func removeAllSublayers(){
        if let sublayers = self.layer.sublayers, !sublayers.isEmpty{
            for sublayer in sublayers{
                sublayer.removeFromSuperlayer()
            }
        }
    }

}

Shadow

4

Swift 5 extension

extension UIView {
    func addInnerShadow() {
        let innerShadow = CALayer()
        innerShadow.frame = bounds
        
        // Shadow path (1pt ring around bounds)
        let radius = self.layer.cornerRadius
        let path = UIBezierPath(roundedRect: innerShadow.bounds.insetBy(dx: 2, dy:2), cornerRadius:radius)
        let cutout = UIBezierPath(roundedRect: innerShadow.bounds, cornerRadius:radius).reversing()
        
        path.append(cutout)
        innerShadow.shadowPath = path.cgPath
        innerShadow.masksToBounds = true
        
        // Shadow properties
        innerShadow.shadowColor = UIColor.black.cgColor
        innerShadow.shadowOffset = CGSize(width: 0, height: 0)
        innerShadow.shadowOpacity = 0.5
        innerShadow.shadowRadius = 2
        innerShadow.cornerRadius = self.layer.cornerRadius
        layer.addSublayer(innerShadow)
    }
}
2

I rewrote @NRitH solution on Swift 3, also slightly refactor it:

final class SideShadowLayer: CAGradientLayer {
    enum Side {
        case top,
        bottom,
        left,
        right
    }

    init(frame: CGRect, side: Side, shadowWidth: CGFloat,
         fromColor: UIColor = .black,
         toColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0),
         opacity: Float = 0.5) {
        super.init()

        colors = [fromColor.cgColor, toColor.cgColor]
        self.opacity = opacity

        switch side {
        case .bottom:
            startPoint = CGPoint(x: 0.5, y: 1.0)
            endPoint = CGPoint(x: 0.5, y: 0.0)
            self.frame = CGRect(x: 0, y: frame.height - shadowWidth, width: frame.width, height: shadowWidth)

        case .top:
            startPoint = CGPoint(x: 0.5, y: 0.0)
            endPoint = CGPoint(x: 0.5, y: 1.0)
            self.frame = CGRect(x: 0, y: 0, width: frame.width, height: shadowWidth)

        case .left:
            startPoint = CGPoint(x: 0.0, y: 0.5)
            endPoint = CGPoint(x: 1.0, y: 0.5)
            self.frame = CGRect(x: 0, y: 0, width: shadowWidth, height: frame.height)

        case .right:
            startPoint = CGPoint(x: 1.0, y: 0.5)
            endPoint = CGPoint(x: 0.0, y: 0.5)
            self.frame = CGRect(x: frame.width - shadowWidth, y: 0, width: shadowWidth, height: frame.height)
        }
    }

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

If you don't mind using clipsToBounds = true, you can create a new CALayer offset just off the edge of your view and add the shadow to THAT view. This is what J.Hunter's answer does.

J.Hunter's code adds a top shadow, here I updated it to Swift 5 and added it to the bottom.

Swift 5:

override func draw(_ rect: CGRect) {
  // Create Inner Shadow. Not sure about efficiency of this.
  // You may want to create a shadowLayer property
  //  and only run this code if it hasn't been created yet.
  let size = rect.size
  clipsToBounds = true // Don't want to see your fake view layer
  let innerShadowLayer: CALayer = CALayer()
  
  // Need to set a backgroundColor or it doesn't work
  innerShadowLayer.backgroundColor = UIColor.black.cgColor
  
  // Position your shadow layer (anchor point is in the center)
  //  on the edge of where your shadow needs to be.
  // In my case this moves the shadow layer to the
  //  bottom edge of my view
  innerShadowLayer.position = CGPoint(x: size.width / 2, y: size.height + (size.height / 2))
  
  // This could be smaller I think, just copying J.Hunter's code...
  innerShadowLayer.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  
  // Normal shadow layer properties you'd use for an outer shadow
  innerShadowLayer.shadowColor = UIColor.black.cgColor
  innerShadowLayer.shadowOffset = CGSize(width: 0, height: 0)
  innerShadowLayer.shadowOpacity = 0.3
  innerShadowLayer.shadowRadius = 3
  
  layer.addSublayer(innerShadowLayer)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.