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
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
}
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With