Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadow layer not resizing when UIView frame changed

Issue Image ScreenShot

class ViewController: UIViewController {
    var shadow : UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        shadow = UIView(frame: CGRect(x: 50,y: 50,width: 150,height:150))
        shadow.backgroundColor = .red
        shadow.dropShadow()
        self.view.addSubview(shadow)

    }

    @IBAction func btnActn(_ sender: Any) {self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)

    }

}

extension UIView {
 func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: 1, height: 1)
        layer.shadowRadius = 2
        layer.shadowPath = UIBezierPath(rect: bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }

}

Shadow layer not resizing when UIView frame changed, how to change equal to the frame size, this is my whole code of UIviewcontroller

like image 258
Jishnu Raj T Avatar asked Apr 28 '18 10:04

Jishnu Raj T


2 Answers

You have many ways to do that:

First: In 'viewWillLayoutSubviews' method, you have to call your shadow method like this. so whenever you changed the frame then you have not worry about layers. This method will auto call whenever you have changed the view:-

override func viewWillLayoutSubviews() {
    shadow.dropShadow()
}

Second: When you are going to re-frame you view size then you have to set "true" for "autoresizesSubviews" like this:

@IBAction func btnActn(_ sender: Any) {
        self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
        self.shadow.autoresizesSubviews = true
    }
like image 113
Jogendar Choudhary Avatar answered Oct 16 '22 05:10

Jogendar Choudhary


Before calling dropShadow, first, try to call layoutIfNeeded

        @IBAction func btnActn(_ sender: Any) {
          self.shadow.frame = CGRect(x: 50,y: 50,width: 150,height: 50)
          self.shadow.layoutIfNeeded()
          self.shadow.dropShadow()
        }
like image 37
garg Avatar answered Oct 16 '22 07:10

garg