0
votes

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

myView.layer.cornerRadius = 2
myView.layer.masksToBounds = false    
    myView.layer.shadowColor = UIColor.black.cgColor
    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? = UIColor.black
    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?

1
I would try putting your VC layer code in viewDidLayoutSubviews instead of viewDidLoad. Your view will be properly sized by that point.Joshua Kaden
(On a side note, I couldn't help but notice that your ShadowView code isn't calling super.layoutSubviews)Joshua Kaden
@JoshuaKaden the code comes from this repo: github.com/NathanWalker/MaterialCard and why must I call super.layoutSubviews?user2636197
It's good OOP practice to call super when overriding. It's the L in SOLID: en.wikipedia.org/wiki/SOLID_(object-oriented_design)Joshua Kaden
@JoshuaKaden viewDidLayoutSubviews fixed it. Post a answer and I will accept :)user2636197

1 Answers

3
votes

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