Search code examples
iosswiftautolayoutcalayer

How setting up shadow of the CALayer breaks AutoLayout constraints?


I have cell's imageView shadow customization:

override func layoutSubviews() {
    moviePosterImageView.layer.shadowOffset = .zero
    moviePosterImageView.layer.shadowColor = UIColor.black.cgColor
    moviePosterImageView.layer.shadowRadius = 5
    moviePosterImageView.layer.shadowOpacity = 1
    moviePosterImageView.layer.masksToBounds = false
    moviePosterImageView.layer.shadowPath = UIBezierPath(rect: moviePosterImageView.bounds).cgPath
}

But it breaks imageView sizes and constraints. Without shadow it works pretty good.

enter image description here


Solution

  • But it breaks imageView sizes and constraints.

    Yes, because you forgot to start by saying

    override func layoutSubviews() {
        super.layoutSubviews() // important
    

    Since autolayout happens in layoutSubviews, if you don’t call super you prevent it from operating.