Hubert Zajączkowski
Hubert Zajączkowski

Reputation: 61

ContainerView with shadow and rounded edges

I would like to create custom ContainerView with shadowed and rounded edges. This ContainerView is in form of small rectangle placed on the top of another UIView. In this peculiar situation neither additional layers nor drawing shadow using CoreGraphics are helpful.

enter image description here

Upvotes: 5

Views: 3099

Answers (2)

Hubert Zajączkowski
Hubert Zajączkowski

Reputation: 61

I found a proper solution. I dropped shadow to ContainerView which is a superclass for every UIView inside. Then, I rounded edges using UIViewController class for this small rectangle area.

class GraphViewController: UIViewController {
    @IBOutlet var graphView: GraphViewRenderer!

    override func viewDidLoad() {
        graphView.layer.cornerRadius = 20.0
        graphView.layer.masksToBounds = true

        super.viewDidLoad()
    }
}

class GraphContainerView: UIView {
    func applyPlainShadow() {
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize.zero
        layer.shadowRadius = 5.0
        layer.shadowOpacity = 0.7
    }

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

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

Upvotes: 1

alexburtnik
alexburtnik

Reputation: 7741

You're wrong that additional views/layers won't help.

You can place roundedContainer with rounded corners into another shadowedView with shadow added to it's layer. To avoid those white corners make sure you set background color to clear somewhere.

Example:

//superview for container with rounded corners
shadowedView.backgroundColor = UIColor.clear //this will fix your white corners issue
shadowedView.layer.shadowColor = UIColor.black.cgColor
shadowedView.layer.shadowOffset = .zero
shadowedView.layer.shadowOpacity = 0.3
shadowedView.layer.shadowRadius = 5.0

//add a container with rounded corners
let roundedView = UIView()
roundedView.frame = baseView.bounds
roundedView.layer.cornerRadius = 10
roundedView.layer.masksToBounds = true
shadowedView.addSubview(roundedView)

Upvotes: 5

Related Questions