user2636197 user2636197 - 1 year ago 137
iOS Question

Swift uiview with rounded corners and drop shadow does not work

I am trying to add rounded corners and drop shadow to my UIView:

myView.layer.cornerRadius = 2
myView.layer.masksToBounds = false
myView.layer.shadowColor =
myView.layer.shadowOffset = CGSize(width: 0, height: 1)
myView.layer.shadowOpacity = 0.4
myView.layer.shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 2).cgPath

But this will make the shadow drop very far on the right and bottom which is wrong.

I am placing this code in ViewDidLoad() since I already have another subclass for my UIView so I want to add the shadow in the VC and not in a subclass

But if I place the code in a subclass it will work:

import UIKit

public class ShadowView: UIView {

open var cornerRadius: CGFloat = 2

open var shadowOffsetWidth: Int = 0
open var shadowOffsetHeight: Int = 2
open var shadowColor: UIColor? =
open var shadowOpacity: Float = 0.4

override open func layoutSubviews() {

layer.cornerRadius = cornerRadius
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)

layer.masksToBounds = false
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = CGSize(width: shadowOffsetWidth, height: shadowOffsetHeight)
layer.shadowOpacity = shadowOpacity
layer.shadowPath = shadowPath.cgPath


But how can I make it work with placing the code in my main VC and not a subclass?

Answer Source

I would try putting your VC layer code in viewDidLayoutSubviews instead of viewDidLoad. Your view will be properly sized by that point.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download